Setup PHP SSH2 Connection from php to remote box on pair networks

1. Download modules

Download Win32 binaries and extract  php_ssh2.dll to the extensions directory

Edit the php.ini file that is being used to include this extension


Generate a pub / private key pair on the server you wish to connect to

ssh-keygen -t rsa -C “”
Generating public/private rsa key pair.
Enter file in which to save the key (/usr/home/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /usr/home/username/.ssh/id_rsa.
Your public key has been saved in /usr/home/username/.ssh/

Copy both the public and private key files to your local box.
Cut and paste the contents into authorized_keys2  file in /usr/home/username/.ssh – creating it if it does not exist.

Create a php program containing the following


/* Notify the user if the server terminates the connection */ function my_ssh_disconnect($reason, $message, $language) {
printf("Server disconnected with reason code [%d] and message: %s\n",$reason, $message);

$methods = array(

'kex' => 'diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1',

'client_to_server' => array(

'crypt' => '3des-cbc',

'comp' => 'none'),


'server_to_client' => array(

'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',

'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('', 22, $methods, $callbacks);

if (!$connection) die('Connection failed');

/* Uncomment to secure even further, you want to get the known host key by getting $fingerprint the first time and then hard coding

$known_host = '4D1B79C97D996C16C3CA50FF2445208B';

$fingerprint = ssh2_fingerprint($connection,


if ($fingerprint != $known_host) {


"Possible Man-In-The-Middle Attack? $fingerprint");



if (ssh2_auth_pubkey_file($connection, 'username',


'S:/sshphp/id_rsa', '')) {

echo "Public Key Authentication Successful\n";

} else {

die('Public Key Authentication Failed');



Comments are closed.