Home > Net >  how to construct loop and write netmiko commands to files using python
how to construct loop and write netmiko commands to files using python

Time:01-22

As per the below script, it adds both commands to output.txt.

Instead how to add "show system" command to output1.txt and "show run" command to output2.txt.

Python Script:

Import program dependencies

from netmiko import ConnectHandler
import getpass

Read from a list of hostnames to connect to

hosts = open('hosts.txt','r')
hosts = hosts.read()
hosts = hosts.strip().splitlines()

Get UserName and password from input

userName = input('Username: ')
passWord = getpass.getpass()

Loop to process hosts in hosts.txt file

for host in hosts:
    # Define device type and connection attributes
    Brocade_ICX = {
        'device_type': 'brocade_fastiron',
        'ip': host,
        'username': userName,
        'password': passWord),
    }
    
    # Netmiko SSH Connection Handler
    net_connect = ConnectHandler(**Brocade_ICX)

    #open file to write command output
    file = open('output.txt', 'w')
    
    # Execute commands
    output = net_connect.send_command('show system')
    output = net_connect.send_command('show run')
    
    # Print output to console screen
    print('-------------- Output from '   host   '------------------')
    print(output)
    print()
    print()
    
    # Write output to file above
    file.write(output)
    file.close()

CodePudding user response:

you are doing the looping wrong..

think about the last iteration of j variable in the loop

it points to c then inner loop goes through each file and and writes c to them

to fix it you need only one loop

for i in range(len(command)):
    file = open(command[i]  '_output.txt', 'w')
    file.write(output[i])
    file.close()

CodePudding user response:

Follow just four simple steps to get the solution.

  1. Opening a text file.

    file = open('text file','w')
    
  2. Adding a test line in the file.

    file.write('We will be seeing aninterated printing of numbers between 0 to 10\n')
    
  3. Writing a for loop over the file.

    for i in range(0,11): 
      file.write(str(i)) 
      file.write('\n') 
    
  4. Closing the text file.

    file.close()
    
  • Related