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:")
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.