Search code examples
pythonpython-2.7automationcisco-iosgetpass

Python Telnet script


Thanks to Python Library i was able to use their example to telnet to Cisco switches, I am using this for learning purposes, specifically learning python.

However, although all the code seem generally easy to read, I am a bit confused as to the following:

1- why use the if statement below 2- why use the "\n" after the username and password write method 3- why am i not getting the output on my bash terminal when the changes are infact committed and successful

HOST = "172.16.1.76"
user = raw_input("Enter your Telnet username : ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST) 

tn.read_until("Username: ") 
tn.write(user + '\n')                <----- 2
if password:                         <----- 1
    tn.read_until("Password: ")
    tn.write(password + "\n")        <------2
tn.write("show run \n") 

time.sleep(5)



output = tn.read_all()              <----- 3
print output  

print "=" * 30
print "Configuration Complete."

I am not sure as to why using the if statement above, typically once you input in the Username, you get the password prompt right afterward. why cant we just type :

tn.read_until("Username: ") 
tn.write(user + '\n')
tn.read_until("Password: ")
tn.write(password + "\n")

As for the second point, why use the '\n' after the passwords and username in the write method if we going to hit enter after we add them anyway?


Solution

  • 1: the line

    password = getpass.getpass()
    

    asks you for you password, if you leave it empty, password will contain the empty string which, in an if statement, is the same as False
    the script doesn't know ahead of time if you have a password on your server or not, it simulates knowing by asking you first and if you don't input anything, it assumes it doesn't (otherwise it would get stuck on tn.read_until("Password: ") forever.

    2: the '\n' simulates you hitting the return key. when you enter your password, for example 'password<RETURN>' the variable password will not contain a trailing newline (\n), this is why it is manually appended

    3: this one i dont know, possibly 5 seconds isn't enough time to wait