处理python中的telnetlib超时错误

时间:2013-03-27 14:05:49

标签: python timeout telnetlib

我正在尝试编写一个python脚本来建立一个telnet连接(使用telnetlib)到一系列主机:

for i in range(len(HOST)):
    print "scanning " + HOST[i] + " ...\n"
    tn = telnetlib.Telnet(HOST[i],23,3)

问题是当其中一个连接超时时,脚本执行会中断并返回以下错误:

Traceback (most recent call last):
  File "C:\Python27\telnet.py", line 24, in <module>
    tn = telnetlib.Telnet(HOST[i],23,3)
  File "C:\Python27\lib\telnetlib.py", line 209, in __init__
    self.open(host, port, timeout)
  File "C:\Python27\lib\telnetlib.py", line 225, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "C:\Python27\lib\socket.py", line 571, in create_connection
    raise err
socket.timeout: timed out

任何人都知道如何跳过此错误并继续脚本?

1 个答案:

答案 0 :(得分:1)

您需要使用try...except块来捕获异常并告诉解释器忽略它。例如:

import socket

for i in range(len(HOST)):
    print "scanning " + HOST[i] + " ...\n"
    try:
        tn = telnetlib.Telnet(HOST[i],23,3)
    except socket.timeout:
        pass

在这种情况下,明确说明要捕获的异常(socket.timeout)是个好主意。套接字可以抛出许多不同类型的异常,因此使用通用except:语句可能会掩盖打开,读取或写入套接字的问题。