Python - SSH连接IP地址列表。连接超时的异常处理

0 投票
1 回答
2110 浏览
提问于 2025-04-18 07:24

我在使用Paramiko的时候遇到了一个处理超时错误的问题。下面是我用来连接的代码。

try:
    dssh = paramiko.SSHClient()
    dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    dssh.connect(IP, username, password)  
    stdin, stdout, stderr = dssh.exec_command('sho run')
    status = 'success'
except paramiko.AuthenticationException:
    status = 'fail'

当一个主机无法连接时,我会收到类似下面的错误信息,然后脚本就会停止运行。

Traceback (most recent call last):
  File "ssh3.py", line 23, in <module>
    dssh.connect(IP, username, password)
  File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 296, in connect
    sock.connect(addr)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 116] Connection timed out

有没有办法可以捕捉到这个错误,让脚本能够从头到尾都运行完呢?

1 个回答

3

当然可以。你只需要捕捉到那个被抛出的异常就行了。

# At the beginning of your code:
import socket

# In your loop
try:
    # Your stuff
# Replace the existing exception handler:
except (socket.error, paramiko.AuthenticationException):
    status = 'fail'

撰写回答