Python脚本:每5分钟自动保存交换机配置
使用Python脚本自动保存交换机配置
本脚本使用Python实现每隔5分钟自动保存交换机配置的功能,利用NetConf和SSH连接交换机,并使用paramiko和ncclient库进行操作。
代码示例:
import datetime
import time
from ncclient import manager
from paramiko import SSHClient, AutoAddPolicy
# 定义交换机IP地址和登录凭据
switch_ip = '192.168.1.1'
username = 'admin'
password = 'password'
# 连接到交换机使用SSH
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect(switch_ip, username=username, password=password)
# 定义保存交换机配置的函数
def save_config():
ssh.exec_command('copy running-config startup-config')
# 使用NETCONF连接到交换机
with manager.connect(host=switch_ip, username=username, password=password, device_params={'name': 'iosxr'}) as m:
# 每5分钟保存一次配置
while True:
time.sleep(300) # 等待5分钟
now = datetime.datetime.now()
print(f'Saving configuration at {now}')
save_config()
代码说明:
- 导入必要的库:
datetime、time、ncclient和paramiko - 定义交换机IP地址、用户名和密码
- 使用
SSHClient连接到交换机 - 定义
save_config()函数,使用ssh.exec_command()执行copy running-config startup-config命令,保存配置 - 使用
manager.connect()连接到交换机,使用NetConf协议 - 使用
while True循环,每5分钟执行一次save_config()函数,保存配置
注意:
- 确保已经安装了
ncclient和paramiko库 - 修改代码中的IP地址、用户名和密码,以匹配您的交换机配置
- 可以根据需要调整保存配置的时间间隔
- 脚本会持续运行,除非手动停止
原文地址: https://www.cveoy.top/t/topic/n9vp 著作权归作者所有。请勿转载和采集!