0

我是 netmiko/Python 脚本的新手,使用在线示例能够制作脚本来进行配置备份。备份被复制到文本文件并保存输出。

目前,此备份是按顺序完成的,它不会一次连接到所有设备并进行备份。我想同时连接到所有设备。

我了解多线程或 concurrent.futures 可以解决此问题enter code here,但到目前为止我无法做到。

任何人都可以建议,如何修改我现有的代码来实现它。下面是代码。

from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException
import getpass
import sys
import time
import os
from datetime import datetime

##getting system date 
day=time.strftime('%d')
month=time.strftime('%m')
year=time.strftime('%Y')
today=day+"-"+month+"-"+year
enter code here
##initialising device
 device = {
'device_type': 'cisco_ios',
'ip': '192.168.100.21',
'username': 'Cisco',
'password': 'Cisco',
'secret':'Cisco',
'session_log': 'log.txt'
}
##opening IP file
ipfile=open("iplist.txt")
print ("Script to take backup of devices, Please enter your credential")
device['username']=input("username ")
device['password']=getpass.getpass()
print("Enter enable password: ")
device['secret']=getpass.getpass()enter code here

##taking backup
for line in ipfile:
 try:
 device['ip']=line.strip("\n")
 print("\n\nConnecting Device ",line)
 net_connect = ConnectHandler(**device)
 net_connect.enable()
 time.sleep(1)

 with open('config.txt') as f:
    cmd = f.read().splitlines()
 print ("Reading the running config ")
 output = net_connect.send_config_set(cmd)
 output4 = "Failed"
 time.sleep(7)    
 filename=device['ip']+'-'+today+".txt"
 folder = os.path.join(today)
 file = os.path.join(folder,filename)
 os.makedirs(folder,exist_ok=True)
 saveconfig=open(file,'w+')
 print("Writing Configuration to file")
 saveconfig.write(output)
 saveconfig.close()
 time.sleep(10)
 net_connect.disconnect()
      
 print ("Configuration saved to file",filename)   
 except:
      print ("Access to "+device['ip']+" failed,backup did not taken")
      output4 = "Failed"
      file= device['ip']+'-'+today+"Error"+".txt"
      config=open(file,'w+')
      config.write(output4)
      config.close()
      
     ipfile.close()
     print ("\nAll device backup completed")enter code here
4

1 回答 1

0

您可以参考下面的脚本并根据您的要求进行修改。在这里,我使用 pythonmultiprocessing连接池中的设备。

#This script will allow for user pick hosts and enter show commands interactively
#
#Enable Multiprocessing
from multiprocessing import Pool
#
#getpass will not display password
from getpass import getpass
#ConnectionHandler is the function used by netmiko to connect to devices
from netmiko import ConnectHandler
#Time tracker
from time import time

#create variables for username and password
#create variables for configs and hosts
uname = input("Username: ")
passwd = getpass("Password: ")
cmd = input("Enter show commands seperated by ',': ")
host = input("Enter the host IPs seperate with space: ")

#This will put hosts and commands entered into list format
hosts = host.split()
cmds = cmd.split(",")

starting_time = time()

#Each member of the pool of 5 will be run through this function
def run_script(host_ip):
    ios_rtr = {
        "device_type": "cisco_ios",
        "ip": host_ip,
        "username": uname,
        "password": passwd,
        }
    #connect to the device via ssh
    net_connect = ConnectHandler(**ios_rtr)
    #print the device IP or Hostname
    print("Connected to host:", host_ip)
    #this for loop is used to iterate through the show commands
    for show_commands in cmds:
        output = net_connect.send_command(show_commands)
        print("Connected to host:", host_ip)
        print(output)
        print('\n---- Elapsed time=', time()-starting_time)

if __name__ == "__main__":
    # Pool(5) means 5 process will be run at a time, more hosts will go in the next group
    with Pool(5) as p:
        print(p.map(run_script, hosts))


#This is the key to sending show commands vs config commands
#show commands --> net_connect.send_command()
#config commmands --> net_connect.send_config_set()
于 2021-12-14T09:10:02.807 回答