Khriz
Khriz

Reputation: 5988

How can I use pem files in php's ssh2 functions

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

Upvotes: 2

Views: 8065

Answers (3)

Mohammed Atif Sami
Mohammed Atif Sami

Reputation: 1140

here is how you can get the public key from private key

$eKey = file_get_contents('/pathto/key.pem');
$key_private = openssl_get_privatekey($eKey);
$keyDet=openssl_pkey_get_details($key_private);
$key_public = openssl_pkey_get_public(array($keyDet['key'],""));
$keyPDet=openssl_pkey_get_details($key_public);

Upvotes: 1

user437265
user437265

Reputation:

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&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.

Upvotes: 3

troelskn
troelskn

Reputation: 117567

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

Upvotes: 2

Related Questions