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