在 sshtunnel.py 中捕获 "Could not open connection to gateway"

Catch "Could not open connection to gateway" in sshtunnel.py

有时使用 sshtunnel.py 设置隧道会失败,因为网关 (ssh_host) 在我第一次连接到它时会抱怨。我想在放弃之前重试几次:

for attempt in range(5):
    try:
        forwarder.start()
    except Exception, e:
        print 'Error (trying again in five seconds):\n' + format(e.message))
        time.sleep(5)
    else:
        break
else:
    print 'Failed to setup a connection to the gateway'
    sys.exit(1)

但是,错误不是'detected'。我看了一眼sshtunnel.py代码,发现following代码捕获了相关的Paramiko异常:

except paramiko.ssh_exception.AuthenticationException:
    self.logger.error('Could not open connection to gateway')
    return

如何在我的 try: 中捕捉到它?

一个 SSHTunnel.py 项目成员 advised 我要将 forwarder._check_is_started() 添加到我的代码中:

for attempt in range(5):
    try:
        forwarder.start()
        forwarder._check_is_started()
    except BaseSSHTunnelForwarderError as e:
        print 'Error (trying again in five seconds):\n' + format(e.message))
        time.sleep(5)
    else:
        break
else:
    print 'Failed to setup a connection to the gateway'
    sys.exit(1)