2012-10-16 48 views
0

這個問題似乎沒有正確的答案。我試圖連接到使用PEM文件在亞馬遜的實例,但我keey獲得:PHP連接到亞馬遜使用Pem

ssh2_auth_pubkey_file(): Authentication failed for ubuntu using public key: Invalid public key 

PEM的文件不具有公共密鑰,所以我提取的私鑰的公鑰。這裏是我的代碼示例:

protected function _createServerSession($host, $user, $password = null, $options = array()) { 

     $defaults = array('port' => 22, 'public_key_file' => '', 'private_key_file' => '', 'key_pass_phrase' => null, 'authentication_method' => 'password', 'pem_file' => null); 
     $options += $defaults; 

     $methods = array(
      'kex' => 'diffie-hellman-group1-sha1', 
      'client_to_server' => array(
       'crypt' => '3des-cbc', 'comp' => 'none' 
      ), 
      'server_to_client' => array(
       'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc', 
       'comp' => 'none') 
     ); 

     $connection = ssh2_connect($host, $options['port'], $methods); 

     if ($connection) { 
      $this -> _connection = $connection; 
     } else { 
      throw new Exception('Cannot connect to server'); 
     } 

     $fingerprint = ssh2_fingerprint($this -> _connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX); 

     if ($options['authentication_method'] == 'pem') { 

      //Get the public and private key from pem file 
      $public_key_res = openssl_pkey_get_public($options['pem_file']); 
      $private_key_res = openssl_pkey_get_private($options['pem_file']); 

      //Get the private key 
      if($private_key_res) { 
       $private_key_array = openssl_pkey_get_details($private_key_res); 
       $private_key = $private_key_array['key']; 
      } else { 
       throw new Exception('Private key required to connect using pem'); 
      } 

      //Get the public key public key. If it does not exist, get the public key from the private key 
      if($private_key && !$public_key_res){ 
       $public_key_res = openssl_pkey_get_public($private_key); 
       $public_key_array = openssl_pkey_get_details($public_key_res); 
       $public_key = $public_key_array['key']; 

      } else { 
       throw new Exception('Public key required to connect using pem'); 
      } 

      //Write the Keys Out To A File 
      $private_key_file = Yii::app()->basePath.'/../tmp/tmp.key'; 
      $public_key_file = Yii::app()->basePath.'/../tmp/tmp'; 
      file_put_contents($private_key_file, $private_key); 
      file_put_contents($public_key_file, $public_key); 

      //Authentickate 
      $authenticated = ssh2_auth_pubkey_file($connection, $user, $public_key_file, $private_key_file); 


      die(); 
     } 
} 

有沒有人成功通過PHP連接到亞馬遜使用PEM文件?如果你有,你可以分享我做錯了什麼?

+0

順便說一句,pem_file正在通過,因爲整個文件已經讀入內存。 –

回答

1

我的推薦:使用phpseclib, a pure PHP SSH implementation。例如。

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

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

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