Zum*_*rio 3 php bash shell shell-exec
我正在尝试从 php 执行 bash 脚本并实时获取其输出。
我正在应用在这里找到的答案:
然而他们不为我工作。
当我以这种方式调用 .sh 脚本时,它工作正常:
<?php
$output = shell_exec("./test.sh");
echo "<pre>$output</pre>";
?>
Run Code Online (Sandbox Code Playgroud)
然而,当做:
<?php
echo '<pre>';
passthru(./test.sh);
echo '</pre>';
?>
Run Code Online (Sandbox Code Playgroud)
或者:
<?php
while (@ ob_end_flush()); // end all output buffers if any
$proc = popen(./test.sh, 'r');
echo '<pre>';
while (!feof($proc))
{
echo fread($proc, 4096);
@ flush();
}
echo '</pre>';
?>
Run Code Online (Sandbox Code Playgroud)
我的浏览器中没有输出。
我还尝试在这两种情况下调用变量而不是脚本,我的意思是:
<?php
$output = shell_exec("./test.sh");
echo '<pre>';
passthru($output);
echo '</pre>';
?>
Run Code Online (Sandbox Code Playgroud)
这是我的 test.sh 脚本:
#!/bin/bash
whoami
sleep 3
dmesg
Run Code Online (Sandbox Code Playgroud)
使用以下内容:
<?php
ob_implicit_flush(true);
ob_end_flush();
$cmd = "bash /path/to/test.sh";
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());
if (is_resource($process)) {
while ($s = fgets($pipes[1])) {
print $s;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
将 test.sh 更改为:
#!/bin/bash
whoami
sleep 3
ls /
Run Code Online (Sandbox Code Playgroud)
解释:
dmesg 需要权限。您需要授予网络服务器的用户权限。就我而言,apache2 是通过 www-data 用户运行的。
ob_implicit_flush(true):打开隐式刷新。隐式刷新将在每次输出调用后导致刷新操作,因此flush()不再需要显式调用。
ob_end_flush():关闭输出缓冲,因此我们可以立即看到结果。