How to let Python code continue after telnet (telnetlib) timeout
I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands.
My Code:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
TNT = telnetlib.Telnet(HOST, 23, 5)
TNT.read_until(b"Username开发者_Python百科:")
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: ")
Error Message:
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
>>>
How can let the program to just notify me that this device isn't reachable and let it continue with the next commands ??
Wrap the operations in a try block, and handle the exception in a catch block.
The exception you're looking for is socket.timeout
. so:
import socket
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except socket.timeout:
sulk()
Which I discovered in this way:
>>> 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>)
It might be that timeout
is too specific. You might instead prefer to catch any IOError
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except IOError:
sulk()
Python terminates your program whenever as exception arrives. For handling exception you need to wrap it in try, catch statements.
Put your telnet statement in try statement and catch exception using except as shown below:
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: ")
精彩评论