getting an iterable output from a telnet client in python
Question: I am trying to write a script to perform validation checks on a network device
(router,switch). I am using telnet to send commands to the device. I store the
output of the command telnetobject.read_until(prompt) into a file and then run
some validation checks over the stored output by iterating over it one line at
a time. Is there a way to iterate over the output without storing it in a
file? the issue is the read_until option gives the output in one string and
the output of the device i am trying to test has an output in a tabular form
which does not have a consistent delimiter on each line.

This is an example: import telnetlib

    
    
    tn=telnetlib.Telnet('ip address')
    pwd='password'
    uid='userid'
    
    tn.read_until("login: ")
    tn.write(uid + "\n")
    tn.read_until("Password:")
    tn.write(pwd +'\n')
    tn.read_until(">",5)
    tn.write('port statistics show' + '\n')
    op1=tn.read_until("*>",5)
    with open ('stattest-temp.txt','w') as stat:
     stat.write(op1)
    

above code was to get a particular output and store it in a file below code is
to iterate over the output..problem is it is in a tabular form and starts with
multiple '_ _ _' characters and each line in the table has different number of
elements if you split it using a delimiter, hence it becomes difficult to
iterate over output from tn.read_until as it is all one giant string'

    
    
    with open ('stattest-temp.txt','r') as f:
    
    
     for line_no,line in enumerate(f):
       if line_no>5:
        if '+---------------------------------+----------------+-----------+-----------+------------+\r' in line:
         break
        else:
         x=line[:-1].split("|")
         #print x
         x1=x[1].strip()
         x2=x[2].strip()
         x3=x[3].strip()
         x4=x[4].strip()
         x5=x[5].strip()
         if x4 =="YES":
           print x1,x4
           print 'Traffic loss observed'
    
         elif x4=="No":
          print "session recovered"
    

I am looking for a way to do part 2 of the above code without having to write
the output to a file


Answer: I think if you split the output string on newline characters, this should
replicate the effect of saving to a file and the iterating through lines.
Basically set this before your `for` loop:

    
    
     f = op1.split('\n')
    
     for line_no,line in enumerate(f):
       if line_no>5:
        if '+---------------------------------+----------------+-----------+-----------+------------+\r' in line:
         break
        else:
         x=line[:-1].split("|")
         #print x
         x1=x[1].strip()
         x2=x[2].strip()
         x3=x[3].strip()
         x4=x[4].strip()
         x5=x[5].strip()
         if x4 =="YES":
           print x1,x4
           print 'Traffic loss observed'
    
         elif x4=="No":
          print "session recovered"
    

