1

I am struggling to send multiple commands to multiple hosts , i am using commands input from a file:

commands.txt

sh ip int bri
sh run
sh ver

hosts.txt

router 1
router 2
router 3

I then run following

from future import print_function from netmiko import ConnectHandler ##For SSH import re import getpass while True: #create loop for whole program username = input ("Enter Username") jumphostpassword = getpass.getpass("Enter Jumphost Password") elif (op == 2): TACACSpassword = getpass.getpass ("Enter TACACS Password") elif(in1=="c"): commandsfile = input ("Please Enter CommandsFile path as c:/example/ \n :") hostsfile = input ("Please Enter Hosts path as c:/example/ \n :") # hosts = open((hostsfile) , "r") hosts = [hosts for hosts in (hosts.strip() for hosts in open(hostsfile)) if hosts] for host1 in hosts: with open ( host1+".txt","w") as file: commands1 = open( (commandsfile), "r+") jumphost = {'device_type': 'linux','ip': '172.27.200.26', 'username': (username),'password': (jumphostpassword)} net_connect = ConnectHandler(**jumphost) output = net_connect.send_command("ssh " +str(host1)) print (output) else: output = net_connect.send_command(TACACSpassword) print (output) output = net_connect.send_command("term leng 0") print (output) cmd1 = [cmd1 for cmd1 in (cmd1.strip() for cmd1 in open(commandsfile)) if cmd1] for cmd1 in commands1: print ("File saved in c:\saad\saad.txt ") output += net_connect.send_config_set(cmd1) print (output) net_connect.disconnect print ("File saved in c:\saad\saad.txt ") file.write(output) file.close() continue

Saadi381
  • 55
  • 1
  • 2
  • 9

1 Answers1

1

Place your IPs in ips.csv file in the following format...

Host
192.168.1.1
192.168.1.2

Then use the following code, usage python code.py -c ips.csv

#!/usr/bin/python

import getpass
import re
import csv
import paramiko
import netmiko
from argparse import ArgumentParser
from netmiko import ConnectHandler

if __name__ == '__main__':
    parser = ArgumentParser(description='Arguments:')
    parser.add_argument('-c', '--csv', required=True, action='store',
                        help='Location of CSV file of IPs')


args = parser.parse_args()

ssh_username = 'yoursshusername'


ssh_password = 'yoursshpassword'

with open(args.csv, 'r') as file:
    reader = csv.DictReader(file)
    for device_row in reader:
        try:
            ssh_session = ConnectHandler(device_type='cisco_ios',
                    ip=device_row['Host'],
                    username=ssh_username, password=ssh_password)
            print '********* {0} *********'.format(device_row['Host'
                    ])

        # Specify your commands here, you can add more commands just follow the same syntax
             print ssh_session.send_command('show running-config | i hostname')
        # Specify exceptions here 
        except paramiko.AuthenticationException:
    print ('{0}'.format(device_row['Host']),"Authenticaiton Problem!")
            pass