Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data using tn.read_all() in python

Tags:

python

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............'
like image 340
Vinod HC Avatar asked Jul 22 '11 12:07

Vinod HC


2 Answers

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.

like image 102
yogi Avatar answered Sep 25 '22 04:09

yogi


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:

  1. Wait for a fixed amount of time between commands. Usually 1 second is a safe bet for most commands.
  2. Parse the output after each command until you find the prompt, then enter the next command, then parse again, and so on.
like image 27
Ishan Arora Avatar answered Sep 26 '22 04:09

Ishan Arora