phpseclib sftp connect with private key and password

Ron Paul picture Ron Paul · Apr 3, 2013 · Viewed 10k times · Source

Is there anyway to connect the sftp with both private key and ftp password by using phpseclib or any other method.

Answer

neubert picture neubert · Apr 3, 2013

It's kinda rare that SFTP servers use both password and publickey authentication. My guess would be that what you most likely have is a password protected private key. If so you can login thusly:

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

$sftp = new Net_SFTP('www.domain.tld');
$key = new Crypt_RSA();
$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));
if (!$sftp->login('username', $key)) {
    exit('Login Failed');
}

print_r($sftp->nlist());
?>

If indeed your server truly is doing both the following should work:

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

$sftp = new Net_SFTP('www.domain.tld');
$key = new Crypt_RSA();
$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));
if (!$sftp->login('username', $key) && !$sftp->login('username', 'password')) {
    exit('Login Failed');
}

print_r($sftp->nlist());
?>