继续显示远程服务器上使用ssh2_exec长时间运行bash的结果



我有什么

这是有效的,但我想得到长期运行的脚本的结果

启动sh脚本,然后调用ajax函数,该函数每2秒检查一次并显示结果。这可能吗?

$connection = ssh2_connect('192.168.1.1', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'sh /test.sh');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);

我要做什么

$connection = ssh2_connect('192.168.1.1', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'sh /test.sh');
$session->stream = $stream;  <-##### Here i save it in a session ###### 
########################################################
I want to save the Stream in a session variable 
and check the result anytime while the process is still running 
Is this possible ?
##########################################################
$stream = $session->stream;   <-##### Here i get it from the session ######  
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);

当我这样做时,我会得到以下错误:

stream_set_blocking() expects parameter 1 to be resource, integer given

好吧,我明白这是不可能的。

我的解决方案是:

在后台运行脚本,并将结果写入output.txt

$stream = ssh2_exec($connection, 'sh /test.sh > output.txt &');

每2秒读取一次输出文件,这样我就可以按照这个过程进行操作了。在脚本的末尾,它将回显"ProcessFinished",所以有了这个标志,你就知道它已经完成了运行,你不必再检查output.txt了。

$stream = ssh2_exec($connection, "cat output.txt");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$processStatus = stream_get_contents($stream_out);
echo $processStatus;

编辑:
如果你也想要错误,你可以把2>&结束时为1

$stream = ssh2_exec($connection, 'sh /test.sh > output.txt 2>&1 &');

相关内容

  • 没有找到相关文章