Search code examples
pythonip-addresstelnettelnetlib

How to ignore telnetlib errors and continue For loop in python


I want to use telnetlib with python to telnet range of IPs so I used this code

import ipaddress
import telnetlib
import time

def looping_ip() :
    for j in range(1, 50, 1):
        ip = "192.168.1.%d" % (j)
        connection = telnetlib.Telnet()
        connection.open(ip)
        connection.read_until("Password:")
        connection.write("admin"+"\n")
        connection.read_eager()
        return True

The problem is when I execute that code if there's an IP isn't available it show this error :

 Traceback (most recent call last):
  File "/root/Desktop/testing.py", line 12, in <module>
    connection.open(ip)
  File "/usr/lib/python2.7/telnetlib.py", line 227, in open
    self.sock = socket.create_connection((host, port), timeout)
  File "/usr/lib/python2.7/socket.py", line 575, in create_connection
    raise err
error: [Errno 110] Connection timed out

I want to ignore any error and continue the loop till I stopped it. please your answer should be with python not any language else.


Solution

  • Try this:

    import ipaddress
    import telnetlib
    import time
    
    def looping_ip() :
        for j in range(1, 50, 1):
            ip = "192.168.1.%d" % (j)
            try:
                connection = telnetlib.Telnet()
                connection.open(ip)
                connection.read_until("Password:")
                connection.write("admin"+"\n")
                connection.read_eager()
                return True
            except:
                continue