6

在 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;
}

并使用这些详细信息来创建连接。

    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;
    }
}

我得到的结果是调用ssh2_auth_pubkey_file().

错误是:

ssh2_auth_pubkey_file(): 使用公钥对 USERNAME 进行身份验证失败:密钥数据无效,不是 base64 编码

密钥上没有密码,我可以通过 CLI ssh 使用这些密钥手动连接到服务器。

我难住了。我需要以某种方式对密钥进行编码吗?建议?

4

2 回答 2

9

您提到的先决条件,即 pubkey 文件没有任何评论,甚至没有尾随换行符是不正确的(当您仔细考虑时,换行符是荒谬的)。

如果你的脚本失败,你有概率。很快偶然发现了 ssh2 错误,当它被编译为 wuth libgcrypt 而不是 openssl 时,它会导致 ssh2 失败。解决方法是使用 openssl 创建 PEM 格式的私钥文件的 PEM 格式副本:

~/.ssh> openssl rsa -in id_rsa -out id_rsa.pem

然后,在 PHP 脚本中的 ssh2_auth_pubkey_file() 中,使用 id_rsa.pem 作为私钥文件而不是 id_rsa,并省略密码。那应该使它起作用。

于 2013-12-22T13:43:07.403 回答
5

好吧,它表明,我在公开提问后找到了答案。在另一个带有开发评论的网站上找到了这个。

d23d23 at gmail dot com说: “公钥必须在一行上,以密钥类型开头,1 个空格,后跟 keydata(没有换行符),后面不能跟注释。这是 libssh2 的限制,所以删除任何多余的使用您的密钥生成工具创建文件后从文件中获取数据。”

因此,即使我使用 openssl 创建私钥和公钥,我也必须对其进行编辑以将其全部与上述密钥类型放在一行中。谢谢。

于 2012-06-13T16:08:07.227 回答