如何在telnet(telnetlib)超时后让Python代码继续

时间:2011-03-19 20:33:39

标签: python timeout telnetlib

我正在使用Python进行使用telnetlib的自动telnet程序。问题是:当我尝试远程登录的设备没有响应时,意味着超时;程序给我超时消息,不会继续下一个命令。

我的代码:

import telnetlib  
HOST = ("x.x.x.x")  
USER = ("xxxxx")  
PWD = ("yyyyy")  
ENABLE = ("zzzzz")  
TNT = telnetlib.Telnet(HOST, 23, 5)                    
TNT.read_until(b"Username:")  
TNT.write(USER.encode('ascii') + b"\n")  
TNT.read_until(b"Password:")  
TNT.write(PWD.encode('ascii') + b"\n")  
TNT.write(b"enable\n")  
TNT.read_until(b"Password:")  
TNT.write(ENABLE.encode('ascii') + b"\n")  
TNT.write(b"terminal length 0\n")  
TNT.write(b"show run\n")  
TNT.write(b"exit\n")  
print (TNT.read_all().decode('ascii'))  
TNT.close()  
raw_input ("Press any Key to Quit: ")  

错误讯息:

Traceback (most recent call last):  
  File "D:\Python\Telnet (Python 2.7) V1.5.py", line 8, in <module>  
    TNT = telnetlib.Telnet(HOST, 23, 5)  
  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  
timeout: timed out  
>>> 

如何让程序只通知我该设备无法访问并让它继续下一个命令?

3 个答案:

答案 0 :(得分:3)

将操作包装在try块中,并在catch块中处理异常。

答案 1 :(得分:3)

Python会在异常到达时终止您的程序。对于处理异常,您需要将其包装在try,catch语句中。

将您的telnet语句放在try语句中并捕获异常,除非如下所示:

import telnetlib  
HOST = ("x.x.x.x")  
USER = ("xxxxx")  
PWD = ("yyyyy")  
ENABLE = ("zzzzz")  
try:
    TNT = telnetlib.Telnet(HOST, 23, 5)                    
except:
    print "<your custom message>"
    pass
TNT.read_until(b"Username:")  
TNT.write(USER.encode('ascii') + b"\n")  
TNT.read_until(b"Password:")  
TNT.write(PWD.encode('ascii') + b"\n")  
TNT.write(b"enable\n")  
TNT.read_until(b"Password:")  
TNT.write(ENABLE.encode('ascii') + b"\n")  
TNT.write(b"terminal length 0\n")  
TNT.write(b"show run\n")  
TNT.write(b"exit\n")  
print (TNT.read_all().decode('ascii'))  
TNT.close()  
raw_input ("Press any Key to Quit: ")  

答案 2 :(得分:2)

您正在寻找的例外是socket.timeout。这样:

import socket
try:
    TNT = telnetlib.Telnet(HOST, 23, 5)
except socket.timeout:
    sulk()

我用这种方式发现了:

>>> try:
...   t = telnetlib.Telnet("google.com", 23, 5)
... except:
...   import sys
...   exc_info = sys.exc_info()
>>> exc_info
(<class 'socket.timeout'>, timeout('timed out',), <traceback object at 0xb768bf7c>)

可能timeout太具体了。您可能更喜欢捕捉任何 IOError

try:
    TNT = telnetlib.Telnet(HOST, 23, 5)
except IOError:
    sulk()