read_all()" to read data from a cisco device. some time it reads the data and sometime it won't read and gives empty string. I tried below 2 commands but still it's not consitently reading data.
data=tn.read_until("exit")
data= tn.read_all()
please give some inputs i am new to python.
code i am using:
_command2='show chassis'
print 'Commands issued............'
#ISSUE COMMANDS VIA TELNET
tn.write("term len 0\r")
#tn.read_until(" ")
#tn.write(_command1+"\r")
tn.write(_command2+"\r")
tn.write("exit\r" )
print 'Read telnet data............'
#READ TELNET DATA
#data=tn.read_eager()
data=tn.read_until("exit")
#data= tn.read_all()
#print data
print 'Telnet data read successfully............'
I too faced the same problem..This would help:
tn = telnetlib.Telnet('64.0.0.1')
tn.write('ls \r\n')
data = ''
while data.find('#') == -1:
data = tn.read_very_eager()
print data
This snippet reads the info after a command being executed. And reads till '#' prompt is shown.
Short answer:
Use time.sleep(1)
in between write
commands
Long answer:
When you enter a command on a Cisco IOS console, it blocks until the command completes. Any input you enter into the console while the command was running is piped into the running command, much like STDIN works on a bash shell. However in bash, if a commands doesn't explicitly read the input, upon the exit of the program bash takes the unconsumed input and interprets it as a shell command. So if you want to run two commands one after another, where the first command does not read from STDIN, you can enter the second command while first command is running, i.e. you don't have to wait for the first command to finish before you enter another command. This sort of a buffering mechanism makes telnet scripting easy and we have grown to expect this from mature shells. Apparently Cisco IOS lacks this feature, and so you have to make sure you don't enter your commands too soon. There are two ways I can think of, to go about it:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With