使用Netmiko

时间:2016-06-23 06:09:47

标签: command router

我正在努力向多个主机发送多个命令,我正在使用从文件输入的命令:

commands.txt中

sh ip int bri
sh run
sh ver

HOSTS.TXT

router 1
router 2
router 3

然后我运行以下

来自 future 来自netmiko import的import print_函数ConnectHandler ##对于SSH导入重新导入getpass而True:#create loop for whole program username = input("输入用户名")jumphostpassword = getpass.getpass("输入Jumphost密码")elif(op == 2):TACACSpassword = getpass.getpass("输入TACACS密码")elif(in1 ==" c"):commandsfile = input("请输入CommandsFile路径为c:/ example / \ n:")hostsfile = input("请输入主机路径为c:/ example / \ n:")#hosts = open((hostsfile)," r")hosts = [主机的主机(hosts.strip()用于open(hosts文件)中的主机)如果主机]对于host1中的host1:open(host1 +" .txt"," w")as file:commands1 = open((commandsfile),&# 34; r +")jumphost = {' device_type':' linux'' ip':' 172.27.200.26' ,'用户名' :(用户名),'密码' :( jumphostpassword)} net_connect = ConnectHandler(** jumphost)output = net_connect.send_command(" ssh" + str(host1))print(输出)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 in open(commandsfile)中的cmd1()cmd1)如果命令1中的cmd1为cmd1]:print("文件保存在c:\ saad \ saad.txt")output + = net_connect .send_config_set(CMD1) print(输出)net_connect.disconnect print("文件保存在c:\ saad \ saad.txt")file.write(输出)file.close()继续

1 个答案:

答案 0 :(得分:0)

将IP以以下格式放置在ips.csv文件中...

Host
192.168.1.1
192.168.1.2

然后使用以下代码,用法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