handling telnetlib timeout error in python

user2215910 picture user2215910 · Mar 27, 2013 · Viewed 10k times · Source

I am trying to write a python script to establish a telnet connection (using telnetlib) to a range of hosts:

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

The problem is when one of the connections times out, the script executions interrupts and returns the following error:

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

Anyone knows how to skip this error and continue the script?

Answer

user849425 picture user849425 · Mar 27, 2013

You need to use a try...except block to catch the exception and tell the interpreter to ignore it. For example:

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

In this case it's a good idea to explicitly state which exception you want to catch (socket.timeout). Sockets can throw many different types of exceptions so using a generic except: statement might mask a problem with opening, reading or writing to the socket.