华为设备监控脚本 - Python 实现
导入所需库
import paramiko from ncclient import manager import time import datetime
定义交换机IP地址和登录信息
switch_ip = '10.1.60.1' username = 'admin' password = 'password'
定义命令文件路径
command_file = 'commands.txt'
定义类来操作交换机
class HuaweiSwitch: def init(self, ip, username, password): self.ip = ip self.username = username self.password = password self.ssh = None self.netconf = None
# 连接交换机
def connect(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)
self.netconf = manager.connect(host=self.ip, port=830, username=self.username, password=self.password, hostkey_verify=False)
# 关闭连接
def close(self):
self.ssh.close()
self.netconf.close_session()
# 执行命令
def execute_command(self, command):
stdin, stdout, stderr = self.ssh.exec_command(command)
output = stdout.read().decode()
return output
# 获取设备状态
def get_device_status(self):
status = {}
status['power'] = self.execute_command('display power')
status['fan'] = self.execute_command('display fan')
status['eth'] = self.execute_command('display eth')
status['cpu'] = self.execute_command('display CPU')
status['memory'] = self.execute_command('display memory')
status['ospf'] = self.execute_command('display OSPF peer b')
return status
# 配置设备日志主机
def configure_log_host(self, host):
netconf_template = '''
<config>
<system>
<log>
<host>{}</host>
</log>
</system>
</config>
'''.format(host)
self.netconf.edit_config(target='running', config=netconf_template)
定义函数来读取命令文件
def read_command_file(file): with open(file, 'r') as f: commands = f.readlines() return [command.strip() for command in commands]
定义函数来分析设备状态结果
def analyze_device_status(status): if 'faulty' in status['fan']: print('Fan status is faulty') if 'faulty' in status['power']: print('Power status is faulty')
连接交换机并执行命令
switch = HuaweiSwitch(switch_ip, username, password) switch.connect() commands = read_command_file(command_file) for command in commands: output = switch.execute_command(command) print(output) switch.close()
每5分钟监控设备状态并输出结果
while True: switch.connect() status = switch.get_device_status() analyze_device_status(status) switch.close() time.sleep(300)
每24h备份配置文件
while True: switch.connect() now = datetime.datetime.now() filename = 'config_{}.txt'.format(now.strftime('%Y-%m-%d_%H-%M-%S')) output = switch.execute_command('display current-configuration') with open(filename, 'w') as f: f.write(output) transport = switch.ssh.get_transport() sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(filename, 'backup/{}'.format(filename)) switch.close() time.sleep(86400)
配置设备日志主机
switch.connect() switch.configure_log_host('10.1.60.2') switch.close()
原文地址: https://www.cveoy.top/t/topic/n35j 著作权归作者所有。请勿转载和采集!