netmiko批量操作华为设备

from concurrent.futures import ThreadPoolExecutor
import time
import netmiko
import os
from threading import Lock
import openpyxl

class net_dev():


def __init__(self,excel_name):
try :
os.mkdir("./log")
except:
pass
self.excel_name = excel_name
self.list = [] # 空列表存储设备信息数据
self.dic = {} # 空字典存储设备信息
self.pool = ThreadPoolExecutor(10) # 初始化线程数量
self.lock = Lock() # 添加线程锁,避免写入数据丢失
self.path = ("./log") # 创建保存log路径
self.mult_config=[] # 创建列表,保存多条命令。用于批量执行命令


def get_dev_info(self):
wb = openpyxl.load_workbook(filename=self.excel_name)
sheet = wb[wb.sheetnames[0]] # 使用sheet的第一页作为工作sheet
max_row = sheet.max_row # 定义最大行
max_colum = sheet.max_column # 定义最大列
row_data = list(sheet.rows) #遍历每一行数据
header_key = [] # 创建空列表存储第一行数据作为字典的key.
for data in range(1,max_colum+1): # 循环查找第一行,最大列的数据.最大列为max_colum+1
header_info = sheet.cell(row=1,column=data).value
header_key.append(header_info)
#print(header_key)
for row in row_data:
dev_info = [] # 创建列表,存储每行的数据
for i in row:
dev_info.append(i.value)
#print(dev_info)
self.dic = dict(zip(header_key,dev_info)) # 将key和每行的数据打包成字典,存储在字典中
#print(self.dic)
self.list.append(self.dic) #将每行的字典数据存储在初始化的列表中。
self.list.pop(0) # 去除第一行的数据
#print (self.list)
for mult_config_tmp in self.list:
#print(mult_config_tmp)
mult_config = mult_config_tmp["mult_command"]
if mult_config != None:
self.mult_config.append(mult_config)
#print(self.mult_config)


def mult_cmd_in(self,ip,user,dev_type,passwd):
try:
devices = {
'device_type': dev_type, # 锐捷os:ruijie_os, 华三:hp_comware 中兴:zte_zxros
'ip': ip,
'username': user,
'password': passwd,
}

connect_dev = netmiko.ConnectHandler(**devices)
cmd_out = connect_dev.send_config_set(self.mult_config,enter_config_mode=False)
with open (ip + ".txt", "w",encoding="utf-8") as tmp_fle:
tmp_fle.write(cmd_out)
print(ip + " 执行成功")

except netmiko.exceptions.NetmikoAuthenticationException:
self.lock.acquire()
with open("登录失败列表", "a", encoding="utf-8") as failed_ip:
failed_ip.write(ip + " 用户名密码错误\n")
print(ip + " 用户名密码错误")
self.lock.release()
except netmiko.exceptions.NetmikoTimeoutException:
self.lock.acquire()
with open("登录失败列表", "a", encoding="utf-8") as failed_ip:
failed_ip.write(ip + " 登录超时\n")
print(ip + " 登录超时")
self.lock.release()

def main(self):
print(self.list)
print(self.mult_config)
for dev_info in self.list:
#print(dev_info)
if dev_info["ip"] != None:
ip = dev_info["ip"]
print(ip)
user = dev_info["user"]
dev_type = dev_info["dev_type"]
passwd = dev_info["password"]
self.pool.submit(self.mult_cmd_in,ip,user,dev_type,passwd)
os.chdir(self.path)
self.pool.shutdown(True)

yc_use = net_dev("设备信息表.xlsx")
yc_use.get_dev_info()
yc_use.main()



posted @ 2022-11-14 22:02  小菜鸟起飞ing  阅读(347)  评论(0编辑  收藏  举报