Search code examples
pythonpexpect

Looping lines in Python PEXPECT


I have a txt file created named "commands.txt" and it contains two commands ( 2 lines)

sh run vlan 158   
sh run vlan 159

i want to run this two command in a switch but only one commands get executed.here is how my script looks like:

 def shvlan(device,child):  
   commandFile = open('commands.txt', 'r') 
   commands = [i for i in commandFile]  
   for command in commands:  
    child.sendline(command)  
    child.expect('.*#')  
    vlans = child.after  
    child.close()  
    print device + ' conn closed'  
    print 'sh run vlan executed'  
    print vlans  
    return vlans                                                                          

Any suggestion why it is taking only 1st line of the .txt file ?


Solution

  • You are closing the connection inside your loop. You have to move that part of code after the loop. Try something like this

     def shvlan(device,child):
         vlans = []
         with open('commands.txt', 'r') as commands: 
             for command in commands:  
                 child.sendline(command)  
                 child.expect('.*#')  
                 vlans.extend(child.after.splitlines())  
    
         child.close()  
         print device + ' conn closed'  
         print 'sh run vlan executed' 
         print vlans  
         return vlans