pythonpython-3.xtelnetlibcisco-ios

python telnet not pressing enter with "\n"


I am working on a script to pull configs from Cisco devices in GNS3. Currently it is using a hard coded IP & port due to another separate issue but this is the code I am currently using.

import getpass
import telnetlib

print "Getting running-config 127.0.0.1:5002"
tn = telnetlib.Telnet("127.0.0.1","5002")

tn.write("terminal length 0\n")
tn.write("show run\n")
tn.write("exit\n")

readoutput = tn.read_until("exit")
saveoutput = open("C:\Programdata\switch.txt","w")
saveoutput.write(readoutput)
saveoutput.write("\n")
saveoutput.close
print tn.read_all()

If I comment out the readouput and saveoutput blocks of code the script runs through as fast as I would expect it to. However once I leave that code in there it just sits and hangs. I have put print() commands in to verify and it hangs on the readoutput line. I have tried both tn.read_all & tn.read_until (without and without a string parameter) and neither works.

Even though the readoutput is not working I know something is occurring because if I telnet into the switch with telnet 127.0.0.1 5002 in a command prompt it comes up without issue as well as being able to progress through my terminal commands.

Edit: I did more testing with this today and found out through the use of a lot of sleep timers and printing to the terminal what was going on. As it turns out for some reason the telnet session is not actually pressing enter when it should. I tried changing the tn.write("text\n") to tn.write("text" + "\n")and even splitting that into two write commands, but none of it works. Below is a telnet session I opened after some failed attempts at making the script work. Note all the commands are just sitting there in line? If I change the readoutput to look for "xit" which is the text on the first line of the ios console, then it will find it in telnet and print everything in the telnet session to that point.

If anyone knows why "\n" is not actually hitting enter I would greatly appreciate the help as this should be my last major hurdle to making the program this script is a part of work.

strong text


Solution

  • The reason for this behaviour is because \n isn't actually carriage return (CR) - it's line feed (LF) in string, and different systems may have different EOL implementation (the most obvious example being Linux's \n versus Windows's \r\n). In case of Cisco IOS, it seems that \r is enough, although I can't currently verify it.

    Try adding \r\n as this is default Telnet behaviour according to the spec, that should work.