ssh2_exec: wait end of a process to run next

2019-02-27 00:07发布

问题:

I am running a command using ssh2_exec, but looks like it runs the $stream2 before the end of $stream1 process. How do I run $stream2 only after the end of $stream1?

<?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:

Problem Solved:

@Barmar proposed me to look at php.net/manual/en/function.ssh2-exec.php#59324

I solved the problem by:

<?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:

the fact that blocking isn't enabled by default is stupid. this is why i like SSH by phpseclib so much better. stuff just works as expected with phpseclib. eg.

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


回答3:

Read everything from the first stream. When it finishes, you know the command is done.

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


标签: php ssh