尝试使用ssh2_auth_pubkey_file()进行连接

时间:2010-08-04 16:11:48

标签: ssh php

我正在尝试制作一个在终端上运行的php脚本,该脚本将通过ssh连接到远程服务器并检索文件。到目前为止这是我的代码

#!/usr/bin/php -q
<?php
$cwd = dirname(__FILE__).'/';
$filename = 'retrive-this.file';
$host = 'hostip';

$connection = ssh2_connect($host, 22, array('hostkey'=>'ssh-rsa'));
$methods = ssh2_auth_pubkey_file($connection, 'remoteuser',
                                 $cwd.'ssh/id_rsa.pub',
                                 $cwd.'ssh/id_rsa', "it's an inception");
var_dump($methods);

//ssh2_scp_recv($connection, "/remote/server/path/to/$filename", $cwd.$filename);
?>

现在我遇到了ssh2_auth_pubkey_file()函数的问题,当我运行脚本时它会返回:

PHP Warning:  ssh2_auth_pubkey_file(): Authentication failed for remoteuser using public key in /home/tonyl/Projects/get-file-ssh.php on line 10
bool(false)

密钥文件具有权限-rw-r--r--(644)。此外,公钥已添加到remoteuser的授权密钥中。我能正常使用ssh命令ssh,所以我不认为这是一个ssh授权问题,但是谁知道。我是ssh和ssh2 php库的新手。

如果我在远程sshd_config文件中启用它,我可以使用ssh2_auth_password()进行连接,但我不想这样做,因为它会降低安全性传输。

关于我能做什么的任何想法。

3 个答案:

答案 0 :(得分:9)

这是php中的已知错误:密码保护的私钥不能用于某些组合。

请参阅:https://bugs.php.net/bug.php?id=58573

  当使用密码保护公钥文件时,ssh2_auth_pubkey_file()被破坏而libssh2是用libgcrypt编译的,这是debian / ubuntu和其他人所做的。我正在研究这个bug的解决方案,但如果你需要这个工作,请用OpenSSL自己重建libssh2。

解决方法可能是存储未加密的私钥。 解密密钥:

openssl rsa -in id_rsa -out id_rsaNOPASSWORD

然后使用文件id_rsaNOPASSWORD而不提供第五个参数'passphrase'。 它可以工作,但你必须小心你的解密密钥文件。无论如何,安全级别并没有真正受到严重影响,因为即使使用加密密钥,您仍然需要将未加密的密码传递给ssh2_auth_pubkey_file函数...

希望它有所帮助。

答案 1 :(得分:0)

这看起来像错误就在这里。 FILE 是不是文件路径呢?所以它看起来像/somedir/somefile.php,你所做的只是在.php的末尾添加一个/所以我认为这不是真的有效。见http://www.php.net/manual/en/language.constants.predefined.php

$cwd = dirname(__FILE__).'/';

另外,其他人一直遇到ssh2_auth_pubkey_file问题 在所有条件下都返回false。您可能想要提交错误报告。我希望能使用这个功能。我不知道如何使用它,因为我不知道如何提供私钥。

我认为您想要的代码是

if (!defined('__DIR__')) {
    $iPos = strrpos(__FILE__, "/");
    define("__DIR__", substr(__FILE__, 0, $iPos) . "/");
}
$cwd=__DIR__ . '/';

并记住,当涉及到远程目录时,您应该使用ssh2_sftp_realpath()。

据报道, dirname()不可靠。

答案 2 :(得分:0)

我已经使用这个功能大约 3 年了,但由于某种原因,我配置的新服务器无法正常工作。当我发现这个的时候,我正要从阳台上跳下来:

ssh-keygen -m PEM -t rsa -b 4096

使用@megar 多年前回答的链接。

希望它能帮助别人,这很难!

相关问题