这个问题似乎没有正确的答案。我正在尝试使用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 :(得分: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');
?>