How to Connect to a Server over ssh from PHP

A small note on how to connect to a remote server from php, run a command and display the results on screen.

The example below uses authorization with a private key:

function ssh_exec($ip, $command) {
$connection = ssh2_connect($ip, 22);
if (ssh2_auth_pubkey_file($connection, 'remote_user', '/home/remote_user/.ssh/id_rsa.pub', '/home/remote_user/.ssh/id_rsa')) {
     $stream = ssh2_exec($connection, $command);
     stream_set_blocking($stream, true);
     $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
     echo "<pre>Results :\n";
     echo stream_get_contents($stream_out)."</pre>";
     fclose($stream);
  } else {
     die('Public Key Authentication Failed');
  }
}

For password authorization use:

ssh2_auth_password($connection, 'remote_user', 'password');

This function is called like this:

<?php
ssh_exec('192.168.1.19', 'df -h');
?>

Tags:

Categories:

Updated: