phpseclib: SSH2 Examples and Notes

Login:

<?php
include('Net/SSH2.php');
include('Crypt/RSA.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}$key = new Crypt_RSA();
$key->loadKey(file_get_contents('privatekey'));
if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}$key = new Crypt_RSA();
$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));
if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}$result = $ssh->login('username',
    array('Password' => 'pass1'),
    array('Verification code' => 'code1')
);
//$result = $ssh->login($username, 'pass1') && !$ssh->login('username', 'code1');
if (!$result) {
    exit('Login failed');
}if (!$ssh->login('username', 'pass1', 'code1')) {
    exit('Login failed');
}
// this does the same thing as the above
//if (!$ssh->login($username, 'pass1') && !$ssh->login('username', 'code1')) {
//    exit('Login failed');
//}
$ssh->login('username');
$ssh->read('User Name:');
$ssh->write("username\n");
$ssh->read('Password:');
$ssh->write("password\n");

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
$ssh->setTimeout(1);
$ssh->read();
$ssh->write("ls -la\n");
echo $ssh->read();
?>

On Failure

If you're absolutely certain that the password / username you've entered are correct it's possible the server isn't using SSH authentication and that what's prompting you for your credentials is the terminal itself. In this scenario you would want to authenticate in the manner demonstrated in the No Authentication example.

Supported Formats

For a discussion of the supported formats see RSA Feature List

Keyboard-Interactive Authentication

When doing password authentication phpseclib tries keyboard-interactive if password auth fails. Only after both fail does $ssh->login() return false. The reason for this is that a lot of systems just prompt for the password via keyboard-interactive. So if your server only has one keyboard-interactive prompt using the password authentication method would be sufficient.

The method utilized in this example is mainly useful when you have multiple keyboard-interactive prompts and need to disambiguate between them. This example utilizes prompt-based disambiguation. One can also distinguish between the various keyboard-interactive prompts via order-based disambiguation. This method is demonstrated in the Multi-Factor example. What'll happen in that example is that password auth will be tried, will presumably fail and then when keyboard-interactive succeeds all subsequent authentications will utilize keyboard-interactive (unless you're trying to auth with an RSA key).

Better Example Wanted

I would provide a better example but have never had direct access to an SSH server that did authentication in this manner nor do I know how to set one up.