parse command output in variable with loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dragrid
    New Member
    • Jan 2009
    • 29

    parse command output in variable with loop

    would like to read and parse certain fields from multiple lines ( say lines 5 and 9 and the first and sixth fields respectively)
    from the variable of the file the command output created
    tried this code below but having problems parsing out_ping
    Code:
    ip_array = ('192.168.1.1', '192.168.1.1', '124.128.x.x')
    for i in ip_array:
        out_ping = os.popen('ping' + ' ' + i, 'r+').read()
        #sys.stdout.flush()
        print out_ping
    
    out_text = ('out_ping',5,9, 'r')    
    for line in out_text:
       z = line.split()
    if line 5 z[0] == "Reply" and line 9 z[6] < 80ms:
            #sys.stdout.writelines(z[2] + reachable + "\n")
            print z[2] + reachable + "\n"  
    else
    print "congested"
    Last edited by bvdet; Mar 13 '09, 03:27 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Your first for loop appears to work OK. Then you create a tuple and iterate on it in another for loop. The first item in the tuple is the string object 'out_ping'. Look at this:
    Code:
    >>> 'out_ping'.split()
    ['out_ping']
    >>>
    The following if statement is indented incorrectly. It only checks the last iteration of the preceding for loop.

    Look at the following and see if you can adapt it for your purpose:
    Code:
    import os
    
    ip_array = ('192.168.1.1',)
    ping_results = []
    for ip in ip_array:
        f = os.popen('ping %s' % (ip), 'r+')
        out_ping = [item.strip() for item in f.readlines() if item.strip()]
        f.close()
        ping_results.append(out_ping)
    
    for result in ping_results:
        chk1 = result[4]
        chk2 = int(''.join([s for s in result[8].split()[-1] if s.isdigit()]))
        if chk1.startswith("Reply") and chk2 < 80:
            print chk1
            print result[8]

    Comment

    Working...