1

我正在将 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  
>>> 

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

4

3 回答 3

3

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

于 2011-03-19T20:36:46.483 回答
3

每当出现异常时,Python 都会终止您的程序。要处理异常,您需要将其包装在 try、catch 语句中。

将您的 telnet 语句放入 try 语句并使用 except 捕获异常,如下所示:

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: ")  
于 2011-03-25T13:11:24.760 回答
3

您正在寻找的例外是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()
于 2011-07-09T16:58:30.983 回答