#! /usr/bin/env python3
# _*_ coding: utf-8 _*_
?
import os
import sys
import json
from datetime import datetime
from netmiko import ConnectHandler
from concurrent.futures import ThreadPoolExecutor as Pool
?
def write_config_file(filename, config_list):
with open(filename, 'w+') as f:
for config in config_list:
f.write(config)
?
def auto_config(net_dev_info, config_file):
ssh_client = ConnectHandler(**net_dev_info['connect']) #把json格式的字典传入
hostname = net_dev_info['name']
hostips = net_dev_info['connect']
hostip = hostips['ip']
print('login ' + hostname + ' success !')
output = ssh_client.send_config_from_file(config_file)
file_name = f'{hostname} + {hostip}.txt'
print(output)
write_config_file(file_name, output)
def main(net_info_file_path, net_eveng_config_path):
this_time = datetime.now()
this_time = this_time.strftime('%F %H-%M-%S')
foldername = this_time
old_folder_name = os.path.exists(foldername)
if old_folder_name == True:
print('文件夹名字冲突,程序终止\n')
sys.exit()
else:
os.mkdir(foldername)
print(f'正在创建目录 {foldername}')
os.chdir(foldername)
print(f'进入目录 {foldername}')
?
net_configs = []
?
with open(net_info_file_path, 'r') as f:
devices = json.load(f) #载入一个json格式的列表,json.load必须传入一个别表
?
with open(net_eveng_config_path, 'r') as config_path_list:
for config_path in config_path_list:
config_path = config_path.strip()
net_configs.append(config_path)
?
with Pool(max_workers=6) as t:
for device, net_config in zip(devices, net_configs):
task = t.submit(auto_config, device, net_config)
print(task.result())
?
?
if __name__ == '__main__':
#net_info_file_path = '~/net_dev_info.json'
#net_eveng_config_path = '~/eve_config_path.txt'
net_info_file_path = input('请输入设备json_inventory文件路径: ')
net_eveng_config_path = input('请输入记录设备config路径的配置文件路径: ')
main(net_info_file_path, net_eveng_config_path)
|