最近做PHP 通过SFTP 连接亚马逊服务器的,发现按照 其他人博客上写的例子
// 连接ssh ,连接有两种方式(1) 使用密码
// (2) 使用秘钥
public function connect(){
$methods['hostkey'] = $this->use_pubkey_file ? 'ssh-rsa' : [] ;
$this->conn = ssh2_connect($this->config['host'], $this->config['port'], $methods);
//(1) 使用秘钥的时候
if($this->use_pubkey_file){
// 用户认证协议
$rc = ssh2_auth_pubkey_file($this->conn,$this->config['user'],$this->config['pubkey_file'],$this->config['privkey_file'],$this->config['passphrase']);
//(2) 使用登陆用户名字和登陆密码
}else{
$rc = ssh2_auth_password( $this->conn, $this->config['user'],$this->config['passwd']);
}
return $rc ;
}
一直报错
Warning: ssh2_connect() [function.ssh2-connect]: Error starting up SSH connection(-5): Unable to exchange encryption keys in
然后按照PHP官方手册上指导的,更改代码为
$methods = array(
'hostkey'=>'ssh-rsa,ssh-dss',
'client_to_server' => array(
'crypt' => 'aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc,blowfish-cbc',
'comp' => 'none'),
'server_to_client' => array(
'crypt' => 'aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc,blowfish-cbc',
'comp' => 'none'));
if($this->use_pubkey_file){
$this->conn = ssh2_connect($this->config['host'], $this->config['port'], $methods);
}else{
$this->conn = ssh2_connect($this->config['host'], $this->config['port']);
}
这样更改就不会报 ssh2_connect 的错误了;
之后有可能会报
Warning: ssh2_auth_pubkey_file() [function.ssh2-auth-pubkey-file]: Authentication failed for XXXXXX using public key: Unable to open public key file in XXXXX on line XX
对于这个错误,首先保证你的公钥和私钥传递正确,如果确认传递正确,发现还报这个错误,那就是公钥和私钥的格式有误
我是用 PuTTYgen 生成的
一定要使用 红框里的公钥,自己手动保存到文件里,注意,不要格式化,直接保存
私钥 也不能使用下方的保存 Save private key 按钮 ,必须使用上面的Export OpenSSH key 保存私钥;
这样就不会报 Authentication failed for XXX using public key 的错误了