Reading the response from ssh2_exec in PHP
I was trying to get PHP to execute commands on a remote server via SSH. Unfortunately the documentation for ssh2_exec doesn’t go into much depth about how to read the result, and the obvious code doesn’t work. If you do this:
$session = ssh2_connect('squirrel.asymptotic.co.uk');
if (!$session) {
die("Failed to connect");
}
if (!ssh2_auth_pubkey_file($session,
'timm',
'/home/timm/.ssh/id_rsa.pub',
'/home/timm/temp/id_rsa')) {
die("Failed to auth");
}
$result = ssh2_exec($session, "ls -l /home/timm");
if ($result === false) {
die("Failed to execute command");
}
print "<pre>".stream_get_contents($result)."</pre>\n";
you get a blank result. The problem is that stream_get_contents doesn’t read the stream until EOF, it just reads whatever data is currently available. To get it to work as expected, you need to add a call to:
stream_set_blocking($result, true);