-- coding: utf-8 --

import paramiko from ncclient import manager import time import datetime

class HuaweiDevice: def init(self, ip, username, password): self.ip = ip self.username = username self.password = password self.ssh = None self.netconf = None

def connect_ssh(self):
    """
    建立SSH连接
    """
    self.ssh = paramiko.SSHClient()
    self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    self.ssh.connect(hostname=self.ip, username=self.username, password=self.password)

def execute_ssh_command(self, command):
    """
    执行SSH命令
    """
    stdin, stdout, stderr = self.ssh.exec_command(command)
    return stdout.read().decode('utf-8')

def connect_netconf(self):
    """
    建立NETCONF连接
    """
    self.netconf = manager.connect(host=self.ip, username=self.username, password=self.password, timeout=10, hostkey_verify=False)

def configure_netconf(self, xml):
    """
    通过NETCONF配置设备
    """
    self.netconf.edit_config(target='running', config=xml)

def save_config(self):
    """
    保存配置文件到本地
    """
    current_time = datetime.datetime.now()
    filename = f"{self.ip}_{current_time.strftime('%Y%m%d%H%M%S')}.cfg"
    sftp = self.ssh.open_sftp()
    sftp.get('/flash:/startup.cfg', filename)
    sftp.close()

def monitor_status(self):
    """
    监控设备状态
    """
    while True:
        current_time = datetime.datetime.now()
        if current_time.minute % 5 == 0:
            result = self.execute_ssh_command('display device')
            if 'Fan1' in result and 'Fan2' in result and ('faulty' in result or 'abnormal' in result):
                print('风扇出现异常状态:faulty')
            if 'Power' in result and ('faulty' in result or 'abnormal' in result):
                print('电源出现异常状态:faulty')
            if 'LACP' in result and ('faulty' in result or 'abnormal' in result):
                print('LACP出现异常状态:faulty')
            if 'CPU Usage' in result and ('faulty' in result or 'abnormal' in result):
                print('CPU出现异常状态:faulty')
            if 'Memory Usage' in result and ('faulty' in result or 'abnormal' in result):
                print('内存利用率出现异常状态:faulty')
            if 'OSPF' in result and ('Full' not in result or 'DR' not in result):
                print('OSPF邻居状态异常')
        if current_time.hour == 0 and current_time.minute == 0:
            self.save_config()
        time.sleep(60)

if name == 'main': device = HuaweiDevice('10.1.1.1', 'admin', 'password') device.connect_ssh() device.connect_netconf() config_xml = """ 10.1.60.2 """ device.configure_netconf(config_xml) device.monitor_status(

华为设备使用python写脚本并加上注释1 脚本执行的监控相关命令从文件中读取命令并执行2代码有层级结构复用率简单易读用类、函数来构建功能3编写脚本用到paramiko、ncclient、time、datetime4个库4 每5分钟对设备的关键运行状态进行监控使用display电源风扇LACPCPU内存利用率OSPF邻居状态并输出结果5 与交换机建立安全连接6 对状态监控结果分析在两个风扇出现异常

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

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