python交换机配置备份
读取filename中的地址,备份配置
ConnectHandler,对设备支持的厂商和设备制造商有局限,如华为设备制造商有华为和华荣,如果是hurong则无法使用该脚本
from netmiko import ConnectHandler
def backup_huawei_device_config(ip, username, password):
device = {
'device_type': 'huawei', # 华为设备类型
'ip': ip,
'username': username,
'password': password,
}
backup_device = "tftp 172.30.64.6 put vrpcfg.zip " + ip + ".zip"
print(f"开始备份{ip}")
with ConnectHandler(**device) as connection:
# 执行"display current-configuration"来获取当前配置
# 执行"tftp"来备份配置
config_output = connection.send_command(backup_device)
print(config_output)
print(f"{ip}备份完成")
# # 将配置保存到本地文件,文件名可以包含IP地址以区分不同设备
# with open(f"{ip}_config.txt", "w") as file:
# file.write(config_output)
# 调用函数备份配置
with open("filename.txt", "r") as file:
# 逐行读取文件内容
for line in file:
# 对每一IP进行处理,并使用strip()方法去除每行末尾的换行符
backup_huawei_device_config(f"{line.strip()}", '****', '****')
from netmiko import ConnectHandler
from openpyxl import load_workbook
def backup_huawei_device_config(ip, username, password):
device = {
'device_type': 'huawei', # 华为设备类型
'ip': ip,
'username': username,
'password': password,
}
backup_device = "tftp 172.30.64.6 put vrpcfg.zip " + row[0].value + ".zip"
print(f"开始备份{backup_device}")
with ConnectHandler(**device) as connection:
# 执行"display current-configuration"来获取当前配置
# 执行"tftp"来备份配置
config_output = connection.send_command(backup_device)
print(config_output)
print(f"{ip}备份完成")
# 加载整个Excel工作簿
wb = load_workbook('20240203132524.xlsx')
# 从工作簿中选择一个工作表
ws = wb['20240203132524']
for row in ws.iter_rows(min_row=2): # 从第一行开始(通常跳过表头)
if row[0].value and row[1].value and row[2] and row[3]: # 检查列是否有值(避免输出空值)
backup_huawei_device_config(f'{row[1].value}', row[2].value, row[3].value)