首先建立excel表格,填入设备相关连接信息,如图:
然后安装excel处理模块openpyxl,用于读取excel文件。安装netmiko模块用于连接交换机。
pip install openpyxl pip install netmiko
完整代码如下,仅实现了ssh,telnet
from netmiko import ConnectHandler from openpyxl import load_workbook import os from sys import exit # 读取excel内设备列表信息 def check_and_get_dev_list(filename, sheet_name): """ filename: 为Excel文件名 sheet_name: 表名 从表格中逐行遍历,获取设备相关信息 """ excel_information = [] sheet_header = [] wb = load_workbook(filename) sh = wb[sheet_name] # 获取最大行数 row = sh.max_row # 获取最大列数 column = sh.max_column data = [] # 获取表头写入列表中方便调用 for data_1 in range(1, column+1): get_sheet_header = sh.cell(row=1, column=data_1).value sheet_header.append(get_sheet_header) # 第一行为表头, 此处 row +1 是pyton循环时不读取最后一个数 for row_1 in range(2, row + 1): # 存储一行信息 sheet_data_1 = dict() # 逐行读取表中的数据 for b in range(1, column + 1): cell = sh.cell(row=row_1, column=b).value # 将数据已字典形式写入 sheet_data_1 中 # if cell != None: sheet_data_1[sheet_header[b-1]] = cell excel_information.append(sheet_data_1) for i in excel_information: if i['ip'] != None: data.append(i) return data # 配置批量备份导出 def cisco_ssh_confbak(): # 创建备份文件夹 try: path = './conf_bak' os.makedirs(path) except FileExistsError: pass res = check_and_get_dev_list('./resource.xlsx', 'Sheet1') for i in res: dev = {'device_type':i['type'], 'host': i['ip'], 'username': i['username'], 'password': i['password'], 'secret': i['enpassword'], 'port': i['port'],} with ConnectHandler(**dev) as conn: conn.enable() if dev['device_type'] == 'cisco_ios': output = conn.send_command(command_string='show run') elif dev['device_type'] == 'huawei' or 'hp_comware': output = conn.send_command(command_string='dis current-configuration') else: print('error') with open('./conf_bak/'+ dev['host'] +'_conf_bak.txt', mode='w', encoding='utf8') as f: print('正在备份:'+dev['host']) f.write(output) print('备份成功!') return 1 a = cisco_ssh_confbak() print(a)
评论前必须登录!
注册