在PHP5.3.3(在CentOS和apache2上)我试图通过PHP脚本连接到SFTP.代码从构造函数中获取密钥和服务器详细信息
function __construct(){
$this->host = 'servername.loc';
$this->port = SFTP_PORT;
$this->auth_user = 'username';
$this->auth_pub = '/data/home/username/.ssh/id_rsa.pub';
$this->auth_priv = '/data/home/username/.ssh/id_rsa';
$this->auth_pass = null;
$this->connection = null;
}
Run Code Online (Sandbox Code Playgroud)
并使用这些详细信息来创建连接.
private function connect(){
if (!($this->connection = ssh2_connect($this->host, $this->port))) {
$this->response = array('code' => "20",
"message" => "Error connecting to SFTP server.");
return false;
}
if (!ssh2_auth_pubkey_file($this->connection, $this->auth_user, $this->auth_pub,
$this->auth_priv, $this->auth_pass)) {
$this->response = array('code' => "40",
"message" => "Error authenticating to SFTP server with key.");
$this->disconnect();
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的结果是调用时出错ssh2_auth_pubkey_file().
错误是:
" ssh2_auth_pubkey_file():使用公钥对USERNAME进行身份验证失败:密钥数据无效,而不是base64编码 "
密钥上没有密码,我可以通过CLI ssh使用这些密钥手动连接到服务器.
我很难过.我需要以某种方式对密钥进行编码吗?建议?
嗯,看来,我在公开提出问题后找到了答案。在另一个带有开发评论的网站上找到了这个。
gmail dot com 的 d23d23说: “公钥必须位于一行中,以密钥类型开头,1 个空格,后跟密钥数据(无换行符),后面不跟注释。这是 libssh2 的限制,因此请删除任何多余的内容使用密钥生成工具创建文件后,从文件中获取数据。”
因此,即使我使用 openssl 创建私钥和公钥,我也必须对其进行编辑,将其全部放在一行上,并使用上面提到的密钥类型。谢谢。
你提到的先决条件,即pubkey文件没有任何注释,甚至没有尾随换行符是不正确的(当你想到它时,换行符很荒谬).
如果你的脚本失败了,你就有了问题.很快就发现了ssh2错误,当ssh2编译为wuth libgcrypt而不是openssl时会导致ssh2失败.解决方法是使用openssl以PEM格式创建PEM格式的私钥文件副本:
~/.ssh> openssl rsa -in id_rsa -out id_rsa.pem
Run Code Online (Sandbox Code Playgroud)
然后,在PHP脚本的ssh2_auth_pubkey_file()中,使用id_rsa.pem作为privkey文件而不是id_rsa,并省略密码.这应该使它工作.