使用Python脚本自动保存交换机配置

本脚本使用Python实现每隔5分钟自动保存交换机配置的功能,利用NetConf和SSH连接交换机,并使用paramikoncclient库进行操作。

代码示例:

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()

代码说明:

  1. 导入必要的库:datetimetimencclientparamiko
  2. 定义交换机IP地址、用户名和密码
  3. 使用SSHClient连接到交换机
  4. 定义save_config()函数,使用ssh.exec_command()执行copy running-config startup-config命令,保存配置
  5. 使用manager.connect()连接到交换机,使用NetConf协议
  6. 使用while True循环,每5分钟执行一次save_config()函数,保存配置

注意:

  • 确保已经安装了ncclientparamiko
  • 修改代码中的IP地址、用户名和密码,以匹配您的交换机配置
  • 可以根据需要调整保存配置的时间间隔
  • 脚本会持续运行,除非手动停止
Python脚本:每5分钟自动保存交换机配置

原文地址: https://www.cveoy.top/t/topic/n9vp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录