pythontelnettelnetlib

Python telnet script with two login passwords input?


This is the first time I am using python so please help... :) This telnet script works fine for me if I know the correct password, but the router on 192.168.1.1 will sometimes boot up with the password: password1 and sometimes with the password: password2, and I need the script to be fully automated so passwords need to be read directly from the script because I want to telnet and log to router no matter if the password is the first or the second one.

import telnetlib
import time

router = '192.168.1.1'
password = 'password1'
username = 'admin'

tn = telnetlib.Telnet(router)
tn.read_until(b"Login: ")
tn.write(username.encode("ascii") + b"\n")
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
print("Successfully connected to %s" % router)
tn.write(b"sh ip int bri\n")
time.sleep(2)
print (type("output"))
output = tn.read_very_eager()
#print(output)
output_formatted = output.decode('utf-8')
print(output_formatted)
print("done")`

How can I modify this code, to make it try out a second password if the first one was not correct, in order to be successfully logged in via telnet in both cases (password1 or password2)?


Solution

  • After writing the first password, tn.write(password...), you need to determine what output corresponds to a correct login. For example, this might be a command prompt ending in "ok >". For an incorrect password, you need to detect output corresponding to another password prompt, for example "Password:" again, or starting again from "Login: ".

    You can then use telnetlib's expect() method to look simultaneously for these 2 outputs by putting them in a list, eg ["ok >", "Password: "]. See pydoc telnetlib. This method returns a tuple (index in list, match object, text read till match). The only item of interest is the first, the index; it will be 0 if "ok >" was seen, 1 if "Password: " was seen, or -1 if neither was seen by some given timeout. You just need to test this value and proceed appropriately.

    index, match, text = tn.expect([b"ok >", b"Password: "], timeout=10)
    if index==-1:
     ... # oops, timeout
    elif index==1:
     ... # need to send password2
    else:
     ... # ok, logged in
    

    Note, the strings passed to expect() are compiled into regular expressions, so beware of using special characters (see pydoc re).