Search code examples
pythonpython-2.7python-3.xtelnet

Python telnet connection failure


I have device that accepts telnet connection to use it with AT commands

This is my code, should be simple I believe but it won't work for some reason I'm fairly new to telnet lib so I don't understand what I am missing here

def connect(self, host, port):
    try:
        Telnet.open(host, port)
        Telnet.write('AT'+"\r")
        if Telnet.read_until("OK"):
            print("You are connected")
    except:
        print("Connection cannot be established")

it always hits the except.

I am also getting the following error when I just try and import telnetlib and run it just with an IP with no port.

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
Telnet.open('192.168.0.1')
TypeError: unbound method open() must be called with Telnet instance as 
first argument (got str instance instead)

I am having problems understanding what does it want me to do.


Solution

  • The constructor for the Telnet class needs to be called:

    import traceback
    
    def connect(self, host, port):
        try:
            telnet_obj = Telnet(host, port) # Use the constructor instead of the open() method.
        except Exception as e: # Should explicitly list exceptions to be caught. Also, only include the minimum code where you can handle the error.
            print("Connection cannot be established")
            traceback.print_exc() # Get a traceback of the error.
            # Do further error handling here and return/reraise.
    
        # This code is unrelated to opening a connection, so your error
        # handler for establishing a connection should not be run if
        # write() or read_until() raise an error.
        telnet_obj.write('AT'+"\r") # then use the returned object's methods.
        if telnet_obj.read_until("OK"):
            print("You are connected")
    

    Related: Python newbie having a problem using classes