【问题标题】:PHP SSH2 ssh2_connectPHP SSH2 ssh2_connect
【发布时间】:2014-09-18 07:12:11
【问题描述】:

所以我从 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...

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

【问题讨论】:

  • 你在哪个操作系统上运行这个?

标签: php ssh libssh2


【解决方案1】:

问题是 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.

【讨论】:

  • 我认为它告诉我 ip 没有退出,这就是它给我带来问题的原因,因为当我提供正确的 ip 时它没有给我错误。
  • 没错。尝试将上面的代码与不正确的主机一起使用,您还会收到更有用的错误消息。
  • 不,我现在使用的代码只是一个空白页,它没有说像无法连接到服务器。
  • 如果您不希望请求失败,您必须在某个时候捕获异常。如果您的代码无法连接,您需要在页面上显示它,当然跳过任何要使用该连接的代码。
猜你喜欢
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 2021-03-31
  • 2012-04-10
  • 2015-07-25
相关资源
最近更新 更多