由于本人无法在Terminal01上进行编写和测试,以下为伪代码,仅供参考。

import paramiko import ncclient import time import datetime

class Device: def init(self, ip, username, password): self.ip = ip self.username = username self.password = password self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(ip, username=username, password=password) self.netconf = ncclient.manager.connect(host=ip, username=username, password=password, device_params={'name': 'huawei'})

def exec_command(self, cmd):
    stdin, stdout, stderr = self.ssh.exec_command(cmd)
    return stdout.read().decode()

def monitor(self):
    power_status = self.exec_command('display power')
    fan_status = self.exec_command('display fan')
    lacp_status = self.exec_command('display lacp statistics eth-trunk')
    cpu_usage = self.exec_command('cpu-usage')
    memory_usage = self.exec_command('memory-usage')
    ospf_status = self.exec_command('display ospf peer brief')
    fan_faulty = True
    for line in fan_status.split('\n'):
        if 'Normal' in line:
            fan_faulty = False
            break
    if fan_faulty:
        print('All fans are faulty!')

def backup_config(self):
    date = datetime.datetime.now().strftime('%Y_%m_%d')
    filename = f'{date}_{self.ip}.zip'
    self.exec_command(f'save configuration to {filename}')
    self.exec_command(f'copy {filename} sftp://10.1.60.2/{filename}')

def enable_netconf(self):
    self.netconf.lock(target='running')
    config = f'<system><netconf><ssh><server><enable/></server></ssh></netconf></system>'
    self.netconf.edit_config(target='running', config=config)
    self.netconf.commit()
    self.netconf.unlock(target='running')

def config_log_host(self):
    self.netconf.lock(target='running')
    config = f'<system><log><host><ip-address>10.1.60.2</ip-address></host></log></system>'
    self.netconf.edit_config(target='running', config=config)
    self.netconf.commit()
    self.netconf.unlock(target='running')

if name == 'main': commands = [] with open('commands.txt', 'r') as f: commands = f.readlines() device = Device('192.168.1.1', 'username', 'password') while True: for cmd in commands: device.exec_command(cmd) device.monitor() if datetime.datetime.now().hour == 0: device.backup_config() device.enable_netconf() device.config_log_host() time.sleep(300) # 5 minute

使用python写一个脚本1 定期对X园区设备X_T1_ACC2的关键运行状态进行监控5min; 电源状态 display power 风扇状态 display fan LACP状态 display lacp statistics eth-trunk CPU、内存利用率 cpu-usage memory-usage OSPF邻居状态 display ospf peer b

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

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