Getting Command Output via SSH2 Functions in PHP

Getting Command Output via SSH2 Functions in PHP

Running command and getting the output via ssh2 is not as straightforward as running command directly using function exec(), it requires a few function calls using “stream”. The following code illustrates how to do it:
// get connection
$conn = ssh2_connect($host, $port);

// login via pub-private keys
ssh2_auth_pubkey_file($conn, $username, $publicKey, $privateKey);

// run command via ssh2
$stream = ssh2_exec($conn, 'php -v');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);

// get the output
echo stream_get_contents($stream_out);
This is simply for my personal note for future reference, but hopefully it can also help who might be looking for solutions for this.

2 Comments

    1. Eric Lin

      Hi Nkiri,

      Thanks for visiting my blog and post questions.

      Have you tried to echo out messages at each step to confirm which step took time? There are three steps I can see:

      1. connect
      2. exec
      3. fetch

Leave a Reply

Your email address will not be published.

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!