ssh2_exec:等待进程下一步运行

时间:2014-07-01 00:07:17

标签: php ssh

我正在使用ssh2_exec运行命令,但看起来它在$ stream1进程结束之前运行$ stream 2。如何在$ stream1结束后运行$ stream 2?

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream1= ssh2_exec($connection, 'command to run');

$stream2 = ssh2_exec($connection, 'command to run 2');

?>

3 个答案:

答案 0 :(得分:2)

解决问题:

@Barmar建议我看一下php.net/manual/en/function.ssh2-exec.php#59324

我通过以下方式解决了问题:

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream1= ssh2_exec($connection, 'command to run');

stream_set_blocking($stream1, true);

// The command may not finish properly if the stream is not read to end
$output = stream_get_contents($stream1);

$stream2 = ssh2_exec($connection, 'command to run 2');

?>

答案 1 :(得分:2)

默认情况下禁用阻止的事实是愚蠢的。这就是为什么我更喜欢SSH by phpseclib。东西只是按照预期与phpseclib一起工作。例如

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('shell.example.com', 22);
$ssh->login('username', 'password');

$output = $ssh->exec('command to run');
$ssh->exec('command to run 2');
?>

答案 2 :(得分:1)

从第一个流中读取所有内容。完成后,您就知道命令已完成。

$stream1= ssh2_exec($connection, 'command to run');
stream_get_contents($stream1); // Wait for command to finish
fclose($stream1);

$stream2 = ssh2_exec($connection, 'command to run 2');