views:

54

answers:

2

Hi,

I need to connect to some Amazon EC2 instances through php's ssh2 functions to get some info and display it on my backoffice.

Is there a way in ssh2 functions to do the same I do when connecting through the command line ssh?

ssh -i path_to_file/key.pem host01-ec2

Thanks

+1  A: 

You can use openssl_pkey_get_public to extract the pub/private keys, and then use ssh2_auth_pubkey_file to authorize.

troelskn
Thanks for the answer (I tried that, and it works if you have both keys), but the thing is when connecting with command line's ssh I only use the private key, the public is retrieved from the host. Do yo know if I can do like that in PHP ssh functions?
Khriz
That sounds odd. You usually have the public key, if you have the private one. Aren't it in your `.ssh` directory?
troelskn
Yes I'm in .ssh folder, but don't worry, probably is an error of the guy that generated the pem for me... Thanks a lot for your answer
Khriz
A: 

You could use phpseclib, a pure PHP SSH implementation, to do this easily enough:

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

$key = new Crypt_RSA();
//$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', $key)) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

phpseclib seems to support quite a few different key formats:

http://www.frostjedi.com/phpbb/viewtopic.php?f=46&amp;t=15226

The fact that ssh2_auth_pubkey_file() requires both the public and private key is silly since 99% of the time the private key has the public key embedded within it. But whatever - it's not like they asked me lol.

notedshow