pexpect output is out of order

932 views Asked by At

Sorry if this is a dumb quesiton, This is my first attempt at python. I wrote a script that reads a list of interfaces from a file, logs into cisco 7600's and then calls a function that pulls the status and running-config of the interfaces. I run 2 commands on each interface. The problem is managing the pexpect output. Some of the interfaces it does exactly what I expect (no pun intended) and others, it doesn't seem to wait for any ouput at all, still others the output from one command ends up showing up after 2 or three other interfaces have been checked. Right now I just have it all outputting to sys.stdout. Once I get it working I will write it out to a file. I've tried using sendline instead of send, I've played with child.timeout, child.maxsize, time.sleep ... I can post output upon request. I'm just trying to keep this from being too long. The code I am having issues with is:

def get_int_conf(child, if_file, dev_type, prompt):
  open_file = "/home/" + if_file

  if dev_type == 'cisco':
      child.logfile = sys.stdout
      with open(open_file, 'r') as int_list:
#
#Pull name from list
#
          for int_name in int_list:
              print "Interface name is %s" % (int_name)
#
#Build correct syntax
#
              match1 = re.search("(Gi|Te)", int_name)
              match2 = re.search("[0-9]+/[0-9]+", int_name)
              if match1 and match2:
                  first_match = match1.group(1)
                  second_match = match2.group()
                  short_nm = first_match + second_match + " \n"
#
# Run show interface status commmand
#
              child.send('sh interface status | in ' + short_nm)
              child.expect(prompt)
              child.send('\n')
#
# Run show run interface command
#
              child.send('sh run interface ' + int_name)
              child.expect(prompt)
              child.send('\n')
  return()
1

There are 1 answers

0
Dan Cornilescu On

Since child is created and used outside the function I'd first make sure it first gets into a "known state", then just alternate sendline and expect statements. Something along these lines used to work for me on a 7600:

child.sendline('term len 0')  # if not already done, else just child.sendline('')
child.expect(prompt)
...
for int_name in int_list:
    ...
    child.sendline('sh interface status | in ' + short_nm)
    child.expect(prompt)
    child.sendline('sh run interface ' + int_name)
    child.expect(prompt)

Maybe stupid, but I'd also check the order of the interfaces in open_file.

Side note: you have access to the string buffers containing what pexpect receives before and after the matched pattern in each child.expect() statement with the following constructs which you can print/process at will:

print child.before
print child.after

You might want to get familiar with them - they're your friends during development/debugging, maybe you can even use them in the actual script implementation.