How to use SSH in php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to use SSH in php

Post by Neo » Sun Feb 28, 2010 11:02 pm

This tutorial will show you how to use the SSH2 functions in PHP to execute commands over SSH. This requires the SSH2 PECL extension to be installed on your server (installation instructions). Keep in mind that as of this time, the extension is in a beta state, so stability is not guaranteed.

Sending commands is fairly straightforward. You just connect, authenticate, then execute commands. Authentication can be done using a password or public key. Executing commands is a little tricky since it returns a stream that you have to handle.

First, we need to connect:

Code: Select all

$ssh = ssh2_connect('127.0.0.1', 22); 
Replace the IP and port with the correct values of the target server. If successful, $ssh now contains a handle to the connection that we will pass to the next functions.

Now we need to authenticate as a user. This can be done using a simple password or using a public key. I'll show you both methods:

Code: Select all

// Using a password
ssh2_auth_password($ssh, 'user', 'password');
 
// Using a public key
ssh2_auth_pubkey_file($ssh, 'user', '/var/www/.ssh/id_rsa.pub', '/var/www/.ssh/id_rsa', 'passphrase'); 
Change the values as necessary. If using a public key, the paths point to your public and private key files, respectively, and the passphrase is used to decrypt the private key if neccessary.

Now that we are connected and authenticated, we can send a command:

Code: Select all

// exec a command and return a stream
$stream = ssh2_exec($ssh, 'whoami');
// force PHP to wait for the output
stream_set_blocking($stream, true);
// read the output into a variable
$data = '';
while($buffer = fread($stream, 4096)) {
    $data .= $buffer;
}
// close the stream
fclose($stream);
// print the response
echo $data; 
In this example, we ran the whoami command and printed the username that we logged into. Once we executed the command, we must read any response from the stream using the fread function. One thing to note is the use of the stream_set_blocking command, which seems to be required. Don't forget to close the stream when you are done using the fclose command!

That's really all there is to it. The SSH2 extension can do many other things not covered in this tutorial, such as file transfers. It can be very useful when you want to automate some remote server administration tasks or something.

Here is a complete code example:

Code: Select all

<?php
if($ssh = ssh2_connect('127.0.0.1', 22)) {
    if(ssh2_auth_password($ssh, 'user', 'password')) {
        $stream = ssh2_exec($ssh, 'whoami');
        stream_set_blocking($stream, true);
        $data = '';
        while($buffer = fread($stream, 4096)) {
            $data .= $buffer;
        }
        fclose($stream);
        echo $data; // user
    }
}
?>
Post Reply

Return to “PHP & MySQL”