2014-07-01 67 views
2

我正在运行一个使用ssh2_exec的命令,但看起来像是在$ stream1进程结束之前运行$ stream2。如何在$ stream1结束后才运行$ stream2?ssh2_exec:等待下一次运行的进程结束

<?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'); 

?> 

回答

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'); 
+0

现在它给了我一个错误的$ stream2线。 PHP警告:ssh2_exec():无法从第28行的XXX.php中的远程主机请求一个频道 – user3780518

+0

当我使用stream_get_contents删除该行时,我得不到任何错误。 – user3780518

+0

对不起,我对ssh2扩展并不熟悉,不知道为什么会发生这种情况,或者如何解决它。 – Barmar

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'); 

?> 
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'); 
?>