此文章是利用Python脚本结合windows计划任务定期对网络设备配置进行备份。
一、Python脚本
脚本如下:
import pandas as pd
from netmiko import ConnectHandler
from datetime import date
import logging
# 设置日志记录
logging.basicConfig(filename='backup_log.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def backup_device(ip, username, password):
try:
device = {
'device_type': 'huawei', #设备类型需要根据设备类型进行更改,例如:cisco设备改成“cisco_ios”,Juniper设备改成“juniper_junos”,H3C设备改成“hp_comware”。
'ip': ip,
'username': username,
'password': password,
}
with ConnectHandler(**device) as connection:
output = connection.send_command('display current-configuration') #根据不同厂商的设备更改查看配置命令。
today = date.today()
filename = f"{today.strftime('%Y-%m-%d')}_{ip}_backup.txt"
with open(filename, 'w') as file:
file.write(output)
logging.info(f"Backup saved to {filename}")
except Exception as e:
logging.error(f"Failed to backup {ip}: {e}")
def main():
# 读取Excel文件,需要在Python脚本所在的文件夹下新建一个excel文件,并填写相应的IP地址、账号、密码登。本次创建文件名称为“huawei.xlsx”。
df = pd.read_excel('huawei.xlsx', engine='openpyxl')
# 遍历每一行
for index, row in df.iterrows():
backup_device(row['ip'], row['Username'], str(row['Password']))
print("Backup completed for all devices.")
if __name__ == "__main__":
main()
excel文件展示
完成以上步骤可以执行python脚本进行测试。执行成功后在python脚本所在的目录下新建相应的配置文件。
二、编写bat脚本,配置windows计划任务
在python所在的文件夹新建txt文件,并改为bat格式。
在文件中添加以下内容:
路径需要根据脚本存放的位置配置。
下一步进行windows计划任务配置:
在windows打开“任务计划程序”,选择“创建基本任务”,输入相应的任务名称,选择定期备份的周期,然后选择启动程序,关联上面配置好的bat脚本即可。
完成上述配置就可以进行测试了。