PHP SSH2 ssh2_connect

时间:2014-07-26 15:23:55

标签: php ssh libssh2

所以我从php.net上看了一个例子来看看php ssh2的工作原理

所以代码是

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
?>

当我输入错误的信息时,它会给我一些错误,而不是告诉我身份验证失败。

错误是

Warning: ssh2_connect(): php_network_getaddresses: getaddrinfo failed: Name not known in 
/var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/ssh2.php on line 2 Warning: ssh2_connect(): Unable to connect to 
shell.example.com on port 22 in /var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/login/ssh2.php on 
line 2 Warning: ssh2_connect(): Unable to connect to shell.example.com in 
/var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/login/ssh2.php on line 2  Warning: 
ssh2_auth_password() expects parameter 1 to be resource, boolean given in /var/zpanel/hostdata/zadmin/public_html/whothehellcareswhatisthis/login/ssh2.php 
on line 4 Authentication Failed...

但是当我提供正确的信息时,它没有给出任何错误。

1 个答案:

答案 0 :(得分:3)

问题是shell.example.com实际上并不存在,并且对ssh2_connect()的调用无法返回资源。

在尝试将资源与ssh2_connect()一起使用之前,您的代码应检查ssh2_auth_password()是否成功建立连接并返回资源。

$connection = ssh2_connect('some.valid.ssh.host', 22);

if (!$connection) {
    throw new Exception("Could not connect to server.");
}

if (!ssh2_auth_password($connection, 'name', 'password')) {
    throw new Exception("Authentication failed!");
}

// SSH connection authenticated and ready to be used.