jump to navigation

Secure Remote Administration with PHP using SSHv2 October 15, 2012

Posted by Tournas Dimitrios in PHP.

PHP comes with many built-in wrappers for various network-protocols that can be used with file-system functions such as fopen(), copy(), file_exists() , file_get_content() and filesize(). In addition to these built-in wrappers , it is possible to extend PHP’s capabilities with secure network-protocol wrappers such as SSL and SSH . Secure Shell (SSH) is a connection protocol for remote login and other network services over a secure “channel” (like command execution –administration– , file transfer , X11 window forwarding , tunneling of other insecure protocols) . There are two SSH versions in use today SSHv1 and SSHv2 , which are not compatible with each other . SSH2 is highly recommended for all uses (administration and/or file-system tasks) .

Although PHP has no build-in support for SSH , it can be extended to support this functionality . Extending PHP can be done with different ways , from installing an SSH2-extension via PECL’s repository (or other repositories) , using a wrapper for the already installed SSH2-extension (PEAR’s SSH2-package) , importing a library into the code , up to compiling  source code into an extension . Most likely  shared hosts haven’t installed/enabled the SSH extension into PHP , but this functionality can be achieved by external libraries , phsecplib is probably the most efficient alternative solution . No matter which method is used for remote login (build-in , PEAR-lib , phpsecLib) the concepts remain the same . This article will present three practical examples for SSH remote administration tasks . Each example will reflect the three aforementioned ways  PHP can be set-up to support SSH (PECL-package , PEAR-package , external libraries) .

Installing the SSH extension on Wamp is simple as downloading  a “dll” from Pier’s repository and moving it into PHP’s “ext” folder .  PHP’s “ini” file should be configured to load the extension  , just with the following directive : extension=php_ssh2.dll  . Lastly , restart the server  .

Prerequisites :   The reader should already be familiar with basic concepts of SSH and remote administration of Linux machines . A Linux box should already be configured to accept SSH-login (OpenSSH is the package for *NIX based Operating systems ) . And of course , a PHP web-server with  SSH support enabled . Tweaking PHP for SSH (installing extensions , packages or libraries )  is left to the reader .  Do a quick phpinfo()  to be sure that PHP has SSH support enabled via an extension , or run the following code-snippet  .

Run the following code to find out which wrappers are available on PHP (build-in and externally loaded).

header('Content-type: text/plain') ;
Results on my Wamp installation:
    [0] => php
    [1] => file
    [2] => glob
    [3] => data
    [4] => http
    [5] => ftp
    [6] => zip
    [7] => compress.zlib
    [8] => https
    [9] => ftps
    [10] => phar
    [11] => ssh2.shell
    [12] => ssh2.exec
    [13] => ssh2.tunnel
    [14] => ssh2.scp
    [15] => ssh2.sftp

First example :   SSH-extension is loaded into PHP .

set_exception_handler('exception_handler') ;
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist") ;
// DNS is also valid , instead of an IP
if(!($con = ssh2_connect("", 22))) {
  throw new Exception("Error : Failed to establish a connection") ;
} else {
// Set username / password
 if(!ssh2_auth_password($con , "root", "1234567")) {
 throw new Exception("Error : unable to authenticate") ;

    } else {
// Output message that we are logged in
    echo "<b>Logged in...........</b><br \>"  ;
// A simple Linux-command (do a listing of the remote directory)
   if (!($stream = ssh2_exec($con , "ls -lah" ))) {
throw new Exception("Error : unable to execute command ") ;
    } else {
// collect returning data from command
stream_set_blocking($stream, true);
$data = "";
while ($buffer = fread($stream , 4096)) {
	$data .= $buffer ;
            fclose($stream) ;
	echo "<pre>" ;
    print_r($data) ;
	echo  "</pre>" ;
// A custom exception handler
function exception_handler($exception) {
 echo "<b>Exception cached :</b> " , $exception->getMessage() , "";

Second example : PEAR’s NET_SSH2 (cloned via GitHub)  . This library requires the SSH2 extension  .

// No need to include other files , ass SSH2.php registers an autoloader
include 'Net/SSH2.php' ;
// Define the command to be executed on remote host
$command = 'ls -lah' ;
//common options
$options = array(
			   'login_name' => 'root' ,
			   'password' => '1234567' ,
			   'hostname' => '',
			   'identity_file' => null,
			   'command' => "$command",
			   'port' => 22
 $ssh = new Net_SSH2_LibSSH2() ;
 $standOut ;
 $standError ;
 $ssh->sshExec($standOut , $standError , $options) ;
 echo "<pre>" ;
 print_r($standOut) ;
 echo  "</pre>" ;

Third example : An external library is used (phpseclib) . Works standalone (no need for SSH2 extension) .

set_exception_handler('exception_handler') ;
include('phpseclib/Net/SSH2.php') ;
// DNS is also valid , instead of an IP
$ssh = new Net_SSH2('') ;
// Set username / password
if (!$ssh->login('root', '1234567')) {
 throw new Exception("Error : unable to authenticate / Login") ;
echo $ssh->exec('pwd') ;
echo "<pre>" ;
echo $ssh->exec('ls -lah') ;
echo  "</pre>" ;
// A custom exception handler
function exception_handler($exception) {
 echo "<b>Exception cached :</b> " , $exception->getMessage() , "";

Just for demonstration , the three examples do  a listing of the remote server’s directory . All kind of administration tasks could be achieved  , of course depending on the login-privileges   . More advanced things could be done (such as public-key-authentication) , but my intention was to “get you started ” into the basic concepts . The following links are a good resource for further reading .

Of course SSH ensures a secure route to the remote host , keep in mind though that security has to be taken very seriously on every “link of the chain” . Could you imagine what could happening if the PHP-script was configured for remotely connecting with root privileges and the box that is hosting the PHP-script was
occupied from an attacker ? Simply , the game is over . Even though the route was secured , the entry-point wasn’t .
Using a web application to execute remote commands is not very safe , because an attacker could somehow gain access the box that is hosting the script . It is a much better idea to expose a limited API to remote clients and not allow them to gain a full privileges shell .

Links :


1. agrace - October 16, 2012

I think the second example is wrong. There’s no exec() or login() methods. You first have to set up a bunch of options. eg.


You then have to call sshExec() as is done here:


tournasdimitrios1 - October 16, 2012

OOpss , copy-pasted the wrong code into the second example , now updated .
Thanks for pointing my error .

2. Justin - October 17, 2012

thank you for searching and sharing information. an excellent blog and an excellent page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s