1

I'm wondering if it is possible to know if my telnet connection is successful?

So, if I'm connected to my switch and if I could write commands

telnet = telnetlib.Telnet(IP)
telnet.read_until(b"User Name:")
telnet.write(b"LOGIN\n")
telnet.read_until(b"Password:")
telnet.write(b"PASSWORD\n")
# Here I want to know if I'm connected
Eduloc
  • 53
  • 2
  • 2
  • 9
  • There is no such option in `telnet` lib, you can parse the server response and check if connection is successful or not, that is if server responds for successful authentication – Harwee Jun 16 '16 at 09:58
  • Actually, I think some of the methods will return an `EOFError` if the connection is lost. So probably you should enclose your code in a `Try/Except` clause. See here: https://docs.python.org/3.5/library/telnetlib.html – Victor Domingos Jun 16 '16 at 10:09
  • @Harwee I used your tip and it is working perfectly ! – Eduloc Jun 16 '16 at 10:33

2 Answers2

1

You could go this way:

def is_connected(telnet_obj ):
    answer = telnet_obj.read_all()
    if "connected" in answer:             #this test condition is not real is an example
        return True
    else:
        return False

If you observe what yout router/switch returns you can test for that condition. In this case testing for the presence of a string or lack in the answer variable.

wind85
  • 487
  • 2
  • 5
  • 11
1

Don't use read_all if you plan on writing something after authentication. It blocks the connection until EOF is reached / connection is closed.

First check the output telnet server is giving when an authentication is successful using putty or something else. read_untill the string to be matched after authentication.

telnet = telnetlib.Telnet(IP)
telnet.read_until(b"User Name:")
telnet.write(b"LOGIN\n")
telnet.read_until(b"Password:")
telnet.write(b"PASSWORD\n")

telnet.read_untill("string to be matched")
Harwee
  • 1,601
  • 2
  • 21
  • 35