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

if (!$session) {
   die("Failed to connect");

if (!ssh2_auth_pubkey_file($session,
                           '/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);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">