SSH2如果登录失败=退出。 PHP

时间:2012-09-04 21:21:24

标签: php

如果登录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);

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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";
}