dongyi2993 2012-09-04 21:21
浏览 19

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

how would i make this code, exit or quit if the login to the ssh2 fails.

            $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条回答 默认 最新

  • doufei7516 2012-09-04 21:25
    关注

    The documentation on ssh2_auth_password() says:

    Returns TRUE on success or FALSE on failure.

    So you can just check if it returns false

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

    While you're doing that, you may also want to add some error checking to the ssh2_connect() call, as it can return a non-resource if it was unable to connect.

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

    Edit for comment

    If you'd like to have it fallback on another login attempt, you can do it a couple of ways. If you'll just have one more set of credentials, you can simply duplicate the if inside of itself.

    //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
        }
    }
    

    Alternatively, if you have a large number of credentials to try, you can store them in an array and loop over it

    $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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度