Question

I'm trying to connect my EC2 instance with ssh2 php module.

I've obtained the public key from known_hosts file (format: "ssh-rsa XXXX..." putted into "public.txt" file) and i'm using the amazon keypair.pem as private key ("-----BEGIN RSA PRIVATE KEY----- XXXX..." in private.pem).

I'm using this php code:

$connection = ssh2_connect('XXXX.eu-west-1.compute.amazonaws.com', 22, array('hostkey'=>'ssh-rsa'));    
if(!ssh2_auth_pubkey_file(
    $connection,
    'ubuntu',
    'public.txt',
    'private.pem'
))
    die("Auth error");  
$sftp = ssh2_sftp($connection);

The error i get is: ssh2_auth_pubkey_file(): Authentication failed for ubuntu using public key: Username/PublicKey combination invalid

What am i doing wrong?

Was it helpful?

Solution

The public key in the known_hosts file isn't the public key you need to be using. Rather, you need to be using the public key from authorized_keys.

That said, the fact that libssh2 even requires the public key is stupid. Honestly, I'd recommend you use phpseclib, a pure PHP SSH2 implementation, over libssh2. eg.

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

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

print_r($ssh->nlist());
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top