代码之家  ›  专栏  ›  技术社区  ›  D4V1D

错误凭据时处理“ssh2_auth_password()”错误

  •  1
  • D4V1D  · 技术社区  · 12 年前

    我有点纠结于如何处理错误 ssh2_auth_password() 函数(和 ssh2_connect() 以及)。我成功地连接并登录到我的远程服务器,然而,当涉及到提供错误的凭据时,我希望能够处理这些情况。我使用的是ZF1.12,我创建了一个小控制器插件,如下所示:

    <?php
    class My_Controller_Plugin_Scp extends Zend_Controller_Plugin_Abstract
    {
        private $host;
        private $login;
        private $password;
        private $destDir = '.';
        private $connexion;
    
        public function __construct()
        {
            $co = ssh2_connect($this->getHost(), 22);
            if(false === $co)
                throw new Exception('Can\'t connect to remote server');
    
            $this->setConnexion($co);
        }
    
        /**
         * @return bool
         * @throws Exception
         */
        public function auth()
        {
            $auth = ssh2_auth_password($this->getConnexion(), $this->getLogin(), $this->getPassword());
    
            if($auth === false)
                throw new Exception('Authentication failed!');
    
            return $auth;
        }
    

    我在控制器中使用这个插件,如下所示:

        try {
            // Préparation à la copie en SSH du fichier template
            $scp = new My_Controller_Plugin_Scp();
            $scp->auth(); // Authentification
        } catch(Exception $e) {
            echo $e->getMessage();
            $this->getHelper('Redirector')->setGotoRoute(array(), 'ficheVoir');
            exit();
        }
    

    实际输出是,当我弄乱凭据时,会抛出PHP警告,而我希望能够显示自定义错误消息。

    有什么我做错了吗 Exception 什么?

    1 回复  |  直到 12 年前
        1
  •  3
  •   Ion Bazan    12 年前

    我无法测试您的代码,因为缺少了很多东西。 我根据你的代码编写了一个简单的连接函数:

    <?php
    
    function connect() {
        $host = '';
        $login = '';
        $password = '';
        $co = ssh2_connect($host, 22);
        if (false === $co)
            throw new Exception('Can\'t connect to remote server');
        $result = @ssh2_auth_password($co, $login, $password);
        var_dump($result);
        if ($result === false) {
            throw new Exception('Authentication failed!');
        }
        echo 'Connection estabilished';
    }
    
    try {
        connect();
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n";
    }
    

    我正在使用 @ 不要抛出难看的PHP错误消息。如果 $result 是 false 一 Exception 被抛出,正在正确处理。基本上,解决方案只是添加 @ 之前 ssh2_auth_password() 作用