0

如果登录 ssh2 失败,我将如何制作此代码、退出或退出。

            $query = mysql_query("SELECT * FROM ssh2");
            while($row = mysql_fetch_array($query)){
            $ip = $row['ip'];
            $user = $row['user'];
            $pass = $row['pass'];
            $ssh = ssh2_connect($ip, 22);
            ssh2_auth_password($ssh, $user, $pass);
4

2 回答 2

2

上的文档ssh2_auth_password()说:

成功时返回 TRUE,失败时返回 FALSE。

所以你可以检查它是否返回 false

if(ssh2_auth_password($ssh, $user, $pass) === false) {
    //do stuff if it can't login
}

在执行此操作时,您可能还想在ssh2_connect()调用中添加一些错误检查,因为如果无法连接,它可能会返回非资源。

$ssh = ssh2_connect($ip, 22);
if($ssh === false) {
    //do stuff if it can't connect
}

编辑评论

如果您想让它回退到另一次登录尝试,您可以通过几种方式来实现。如果您只拥有一组凭据,则可以简单地复制其if内部。

//try the first login
if(ssh2_auth_password($ssh, $user, $pass) === false) {
    //try the second set
    if(ssh2_auth_password($ssh, $user2, $pass2) === false) {
        //do stuff if it can't login
    }
}

或者,如果您有大量凭据要尝试,您可以将它们存储在一个数组中并循环遍历它

$creds = array(
    array('user' => $user, 'pass' => $pass),
    array('user' => $user2, 'pass' => $pass2),
    //etc
);

$logged_in = false;
foreach($creds as $cred) {
    if(ssh2_auth_password($ssh, $cred['user'], $cred['pass'])) {
        $logged_in = true;
        break;
    }
}

if(!$logged_in) {
    //do stuff when you can't login
}
于 2012-09-04T21:25:39.880 回答
0

我更喜欢对这样的事情使用异常:

try {
    if (!$query = mysql_query("SELECT * FROM ssh2")) {
        throw new Exception("MySQL query failed.");
    }
    while($row = mysql_fetch_array($query)){
        $ip = $row['ip'];
        $user = $row['user'];
        $pass = $row['pass'];
        $ssh = ssh2_connect($ip, 22);
        if ($ssh === false) {
            throw new Exception("Connection to $ip:22 failed");
        }
        if (ssh2_auth_password($ssh, $user, $pass) === false) {
            throw new Exception("Password failed for user '".$user."'");
        }
    }
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
于 2012-09-04T21:53:31.507 回答