导入必要的模块

import paramiko # SSH连接模块 import ncclient # NETCONF连接模块 import time # 时间模块 import datetime # 日期时间模块

定义华为设备类

class HuaweiDevice: # 初始化华为设备类,需要传入设备的IP地址、用户名和密码 def init(self, ip, username, password): self.ip = ip self.username = username self.password = password self.ssh = None # SSH连接对象 self.netconf = None # NETCONF连接对象

# SSH连接方法
def connect_ssh(self):
    self.ssh = paramiko.SSHClient() # 创建SSH客户端对象
    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 自动添加新主机的密钥
    self.ssh.connect(self.ip, username=self.username, password=self.password) # SSH连接

# SSH断开连接方法
def disconnect_ssh(self):
    if self.ssh: # 如果已经连接,则关闭连接
        self.ssh.close()
        self.ssh = None

# SSH执行命令方法
def execute_ssh_command(self, command):
    if not self.ssh: # 如果未连接,则先连接
        self.connect_ssh()
    stdin, stdout, stderr = self.ssh.exec_command(command) # 执行SSH命令
    return stdout.readlines() # 返回命令输出结果

# NETCONF连接方法
def connect_netconf(self):
    self.netconf = ncclient.manager.connect(
        host=self.ip,
        port=830,
        username=self.username,
        password=self.password,
        hostkey_verify=False
    )

# NETCONF断开连接方法
def disconnect_netconf(self):
    if self.netconf: # 如果已经连接,则关闭连接
        self.netconf.close_session()
        self.netconf = None

# NETCONF执行命令方法
def execute_netconf_command(self, command):
    if not self.netconf: # 如果未连接,则先连接
        self.connect_netconf()
    return self.netconf.edit_config(target='running', config=command) # 执行NETCONF命令并返回结果

# 监控设备方法,需要传入设备名称
def monitor_device(self, device_name):
    while True: # 循环监控
        # # 电源状态
        # power_status = self.execute_ssh_command(f"display device {device_name} power")
        # print("Power status:")
        # print(power_status)
        #
        # # 风扇状态
        # fan_status = self.execute_ssh_command(f"display device {device_name} fan")
        # print("Fan status:")
        # print(fan_status)

        # LACP状态
        lacp_status = self.execute_ssh_command(f"display lacp statistics eth-trunk")
        print('LACP status:')
        print(lacp_status)

        # CPU、内存利用率
        cpu_usage = self.execute_ssh_command(f"display cpu-usage")
        print('CPU usage:')
        print(cpu_usage)
        memory_usage = self.execute_ssh_command(f"display memory-usage")
        print('Memory usage:')
        print(memory_usage)

        # OSPF邻居状态
        ospf_status = self.execute_ssh_command("display ospf peer")
        print('OSPF status:')
        print(ospf_status)

        # # 判断风扇状态是否异常
        # fan_status = [line.strip() for line in fan_status if line.strip()]
        # if len(fan_status) >= 2 and all("Normal" not in line for line in fan_status):
        #     print("All fans are faulty!")

        time.sleep(300) # 等待5分钟

# 备份配置方法,需要传入设备名称
def backup_config(self, device_name):
    now = datetime.datetime.now().strftime("%Y_%m_%d") # 获取当前日期时间
    backup_filename = f"{now}_{device_name}" # 备份文件名
    config_filename = f"{backup_filename}.zip" # 压缩文件名
    backup_command = f"save configuration to {backup_filename}.cfg\n" # 保存配置命令
    backup_command += f"file compress {backup_filename}.cfg {config_filename}\n" # 压缩命令
    self.execute_netconf_command(backup_command) # 执行备份命令

    # 通过SFTP下载文件到本地
    transport = paramiko.Transport((self.ip, 22)) # 创建SFTP连接
    transport.connect(username=self.username, password=self.password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.get(config_filename, config_filename) # 下载备份文件
    sftp.close()
    transport.close()

# 启用NETCONF方法
def enable_netconf(self):
    command = """
        <config>
            <netconf xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
                <enabled>true</enabled>
            </netconf>
        </config>
    """
    self.execute_netconf_command(command) # 执行NETCONF命令以启用NETCONF

# 配置日志服务器方法,需要传入设备名称和日志服务器IP地址
def configure_log_server(self, device_name, log_server_ip):
    command = f"""
        <config>
            <logging xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
                <host>
                    <name>{log_server_ip}</name>
                    <device-device-id>{device_name}</device-device-id>
                </host>
            </logging>
        </config>
    """
    self.execute_netconf_command(command) # 执行NETCONF命令以配置日志服务器

if name == 'main': device = HuaweiDevice(ip="192.168.1.1", username="admin", password="password") # 实例化华为设备类 device.enable_netconf() # 启用NETCONF device.configure_log_server(device_name="X_T1_ACC2", log_server_ip="10.1.60.2") # 配置日志服务器 device.monitor_device(device_name="X_T1_ACC2") # 监控设备 device.backup_config(device_name="X_T1_ACC2") # 备份配置

Python 华为设备管理脚本:使用 SSH 和 NETCONF 实现监控、备份和日志配置

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

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