SSH connection with PHP


To create an SSH connection with PHP, There are several ways:

The clean solution: Connecting to PHP-SSH2

To do so she must install the package PHP-ssh2 automatic installation routine running smooth, see php.net.

    $connection = ssh2_connect($host, $port);
    if(ssh2_auth_password($connection, $user, $password)){
        $stream = ssh2_exec($connection, $command);
        stream_set_blocking($stream, false);
        $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
        $result = stream_get_contents($stream_out);
    }

Quick and dirty: Connect with exec()

Simply using the console of operating system (sshpass should be installed, so that the password can be specified with).

$command = 'sshpass -p "'
    . $password
    . '" ssh -p '.$port.' '
    . $user. '@'. $host. ' "'
    . $sshCommand.'" ';
$result = exec($command);

Bypass fingerprint changing ports

$command = 'sshpass -p "'
    . $password
    . '" ssh -p '.$port.' -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '    
    . $user. '@'. $host. ' "'
    . $sshCommand.'" ';
$result = exec($command);

The example is using the parameter

-o UserKnownHostsFile = / dev/null-o StrictHostKeyChecking = no

the fingerprint validation bypass, what you should not do in live operation, or. You should get before the fingerprint on the console of the server, and then you do not need these parameters.