导入需要的库

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

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

# 关闭SSH连接
def close_ssh(self):
    self.ssh.close()

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

# 关闭NETCONF连接
def close_netconf(self):
    self.netconf.close_session()

# 执行命令并返回输出结果
def run_command(self, command):
    stdin, stdout, stderr = self.ssh.exec_command(command)
    output = stdout.read().decode()
    return output

定义函数,用于读取命令文件并执行命令

def execute_commands(device, filename): with open(filename, 'r') as f: commands = f.readlines() for command in commands: output = device.run_command(command.strip()) print(output)

定义函数,用于监控设备状态并输出结果

def monitor_device_status(device): # 获取当前时间 now = datetime.datetime.now() # 获取设备关键状态并输出结果 power = device.run_command('display power') fan = device.run_command('display fan') eth = device.run_command('display eth') cpu = device.run_command('display CPU') memory = device.run_command('display memory') ospf_peer = device.run_command('display OSPF peer b') print('Power: ' + power) print('Fan: ' + fan) print('Eth: ' + eth) print('CPU: ' + cpu) print('Memory: ' + memory) print('OSPF Peer: ' + ospf_peer) # 判断风扇状态是否异常 if 'faulty' in fan: print('Fan is faulty!') # 每24小时保存一次配置文件并备份在电脑本地 if now.hour == 0 and now.minute == 0: with open('config.cfg', 'w') as f: config = device.run_command('display current-configuration') f.write(config) transport = paramiko.Transport(device.ip, 22) transport.connect(username=device.username, password=device.password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.put('config.cfg', 'config_backup.cfg') sftp.close() transport.close()

实例化HuaweiDevice类并连接设备

device = HuaweiDevice('192.168.1.1', 'admin', 'password') device.connect_ssh() device.connect_netconf()

每5分钟监控一次设备状态并输出结果

while True: monitor_device_status(device) time.sleep(300)

关闭连接

device.close_ssh() device.close_netconf()

华为设备监控脚本-Python实现

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

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