Bash 从 PHP 执行的脚本实时输出
Bash script live output executed from PHP
我正在尝试从 php 执行 bash 脚本并实时获取其输出。
我正在应用找到的答案 here:
但是他们对我不起作用。
当我以这种方式调用 .sh 脚本时,它工作正常:
<?php
$output = shell_exec("./test.sh");
echo "<pre>$output</pre>";
?>
然而,在做的时候:
<?php
echo '<pre>';
passthru(./test.sh);
echo '</pre>';
?>
或:
<?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>';
?>
我的浏览器没有输出。
我也尝试在这两种情况下调用变量而不是脚本,我的意思是:
<?php
$output = shell_exec("./test.sh");
echo '<pre>';
passthru($output);
echo '</pre>';
?>
这是我的 test.sh 脚本:
#!/bin/bash
whoami
sleep 3
dmesg
使用以下内容:
<?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;
}
}
?>
将test.sh更改为:
#!/bin/bash
whoami
sleep 3
ls /
解释:
dmesg 需要权限。您需要为此授予网络服务器的用户权限。在我的例子中,apache2 是通过 www-data 用户运行。
ob_implicit_flush(true)
:打开隐式刷新。隐式刷新将在每次输出调用后执行刷新操作,因此不再需要对 flush()
的显式调用。
ob_end_flush()
:关闭输出缓冲,因此我们会立即看到结果。
我正在尝试从 php 执行 bash 脚本并实时获取其输出。
我正在应用找到的答案 here:
但是他们对我不起作用。
当我以这种方式调用 .sh 脚本时,它工作正常:
<?php
$output = shell_exec("./test.sh");
echo "<pre>$output</pre>";
?>
然而,在做的时候:
<?php
echo '<pre>';
passthru(./test.sh);
echo '</pre>';
?>
或:
<?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>';
?>
我的浏览器没有输出。
我也尝试在这两种情况下调用变量而不是脚本,我的意思是:
<?php
$output = shell_exec("./test.sh");
echo '<pre>';
passthru($output);
echo '</pre>';
?>
这是我的 test.sh 脚本:
#!/bin/bash
whoami
sleep 3
dmesg
使用以下内容:
<?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;
}
}
?>
将test.sh更改为:
#!/bin/bash
whoami
sleep 3
ls /
解释:
dmesg 需要权限。您需要为此授予网络服务器的用户权限。在我的例子中,apache2 是通过 www-data 用户运行。
ob_implicit_flush(true)
:打开隐式刷新。隐式刷新将在每次输出调用后执行刷新操作,因此不再需要对 flush()
的显式调用。
ob_end_flush()
:关闭输出缓冲,因此我们会立即看到结果。