【问题标题】:Handle 'ssh2_auth_password()' error upon wrong credentials处理错误凭据时的“ssh2_auth_password()”错误
【发布时间】:2014-09-12 23:28:05
【问题描述】:

在处理ssh2_auth_password() 函数(以及ssh2_connect())上的错误时,我有点挣扎。我成功地连接并登录到我的远程服务器,但是,当涉及到提供错误的凭据时,我希望能够处理这些情况。我正在使用 ZF 1.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 之类的东西我做错了吗?

【问题讨论】:

  • 错误信息是什么意思?
  • 它按预期显示Warning: ssh2_auth_password(): Authentication failed for login using password,因为我提供了错误的凭据。
  • 这可能很愚蠢,但尽量不要将返回值分配给$auth 变量并从if 调用函数。另外,请尝试使用 @ 抑制错误。
  • 我已经尝试不将$auth 分配给return 并使用@ 抑制错误,但我留下了一个空白页,而不是转到catch() 表达式。跨度>

标签: php zend-framework ssh exception-handling basic-authentication


【解决方案1】:

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

<?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 警告,以免抛出难看的 PHP 错误消息。如果$resultfalse 则抛出Exception 并得到正确处理。基本上,解决方案就是在ssh2_auth_password()函数之前添加@

【讨论】:

  • 感谢您的echo $e-&gt;getMessage(),我可以看到它确实进入了catch() 表达式,但不知何故,它不想执行Zend Redirector Helper。我正在对此进行调查。谢谢。
  • 嗨!我已经设法修改 Zend Redirector Helper 以便在 catch{} 表达式中工作。这是我的做法:stackoverflow.com/questions/24887138/…
猜你喜欢
  • 2018-09-19
  • 2019-12-02
  • 2015-12-04
  • 2020-03-10
  • 2011-10-27
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多