捕获或抑制模块引发的异常的回溯

Capture or supress trackback from exception raised by module

在下面的代码中,它仍然打印来自一个特定异常的引用通告,即使它被 try/except 捕获。我不知道为什么。

如果 SSH 连接出现任何异常,代码将继续并简单地通知失败。除了在一个 secnario 之外,这按预期工作。

有时,由于我无法控制的网络原因,paramiko 模块出现 socket.timeout 异常。此异常按预期被 try except 块捕获,但引用仍然被转储到控制台。值得注意的是,trackback 包含通常不打印的 socket.timeout 和 SSHException 文本。

我想在一个变量中捕获这个 trackback 以进行记录,或者简单地抑制它而不是窃听输出。

from paramiko import SSHClient, AutoAddPolicy, SSHException


def test_ssh_login (host_info, sshport = 22):
    test_passed = False
    try:                                                                                                            
        client = SSHClient()
        client.set_missing_host_key_policy(AutoAddPolicy())
        client.connect(host_info['host'], username = host_info['user'], password = host_info['pass'], port = sshport )
    except:
        print(f"[failed] ssh {host_info['user']}@{host_info['host']} port: {sshport} using password : {host_info['pass']}")
        return False

    else:
        if client.get_transport() is not None:
            if client.get_transport().is_authenticated():
                test_passed = True                                                                                              finally:
        client.close()
        return test_passed


test_host_info = {'host': '192.168.0.1', 'user': 'username', 'pass': "SomePassword"}

if (test_ssh_login(test_host_info)):
    print(f"successful connection with { test_host_info }")

代码按预期工作,超时的原因并不是真正的问题。

只是想知道为什么文本会出现在控制台中,而不是其他部分。

Exception: Error reading SSH protocol banner
Traceback (most recent call last):
  File "/home/user/Code/Python/venv/lib/python3.9/site-packages/paramiko/transport.py", line 2211, in _check_banner
    buf = self.packetizer.readline(timeout)
  File "/home/user/Code/Python/venv/lib/python3.9/site-packages/paramiko/packet.py", line 380, in readline
    buf += self._read_timeout(timeout)
  File "/home/user/Code/Python/venv/lib/python3.9/site-packages/paramiko/packet.py", line 622, in _read_timeout
    raise socket.timeout()                                                                                                  socket.timeout

During handling of the above exception, another exception occurred:                                                                                                                                                                                     Traceback (most recent call last):
  File "/home/user/Code/Python/venv/lib/python3.9/site-packages/paramiko/transport.py", line 2039, in run
    self._check_banner()
  File "/home/user/Code/Python/venv/lib/python3.9/site-packages/paramiko/transport.py", line 2215, in _check_banner
    raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

嗯,我想通了。

我需要捕获 SSHexception 和附加的 EOFError 并将它们都扔到日志中。

try:
                # connect
        client.connect(host_info['host'], username = host_info['user'], password = host_info['pass'], port = sshport )
    except socket.timeout:
        print("[Socket Timeout]")
    except Exception:
        print(f"[failed] ssh {host_info['user']}@{host_info['host']} port: {sshport} using password : {host_info['pass']}")
    except EOFerror:
        pass