Python 脚本:自动监控网络设备运行状态并备份配置
Python 脚本:自动监控网络设备运行状态并备份配置
本脚本使用 Python 语言实现网络设备运行状态自动监控功能,包括监控电源状态、风扇状态、LACP 状态、CPU 和内存使用率以及 OSPF 邻居状态。脚本还会定期备份设备配置并提供安全的文件传输协议以确保数据安全。
功能概述
-
定期对 X 园区设备 X_T1_ACC2 的关键运行状态进行监控(5min):
- 电源状态
display power - 风扇状态
display fan - LACP 状态 (
display lacp statistics eth-trunk) - CPU、内存利用率
cpu-usagememory-usage - OSPF 邻居状态
display ospf peer brief
- 电源状态
-
与交换机之间应建立较为安全的管理。
-
对状态监控结果进行分析,并在风扇出现异常状态时(两个风扇状态全部为非'normal')给出 明确提示:'All fans are faulty!'
-
脚本所执行的监控相关命令不直接在代码中固定,而是以文件的形式保存,脚本从文件中读取 命令并执行。
-
每隔 24h 保存一次 X_T1_ACC2 的配置文件,并通过安全的文件传输协议将配置文件备份在电 脑本地,以【当天日期_设备名称】的名称命名,设备端以及本地的配置文件,如:
2022_07_20_X_T1_ACC2.zip、2022_07_20_X_T1_ACC2.bak; -
代码应有较好的层级结构以及复用率,应使用类、函数来构建上述功能,编写以上脚本你可能 用到
paramiko、ncclient、time、datetime等,python 编译环境以及所需的运行库内容:,需要自行安装配置。
示例脚本
import datetime
import paramiko
import time
class Device:
def __init__(self, name, ip, username, password):
self.name = name
self.ip = ip
self.username = username
self.password = password
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(ip, username=username, password=password)
def execute(self, command):
stdin, stdout, stderr = self.client.exec_command(command)
output = stdout.read().decode()
return output
def monitor(self):
# read commands from file
with open('commands.txt', 'r') as f:
commands = f.readlines()
# execute commands and save results
results = []
for command in commands:
result = self.execute(command.strip())
results.append(result)
# analyze fan status
fan_status = [r for r in results if 'fan' in r]
if len(fan_status) == 2 and 'normal' not in fan_status:
print('All fans are faulty!')
# backup configuration file
if datetime.datetime.now().hour == 0:
timestamp = datetime.datetime.now().strftime('%Y_%m_%d')
filename = f'{timestamp}_{self.name}.cfg'
backup_filename = f'{timestamp}_{self.name}.bak'
self.execute(f'save configuration to {filename}')
self.execute(f'backup configuration to {backup_filename}')
def close(self):
self.client.close()
if __name__ == '__main__':
device = Device('X_T1_ACC2', '192.168.1.1', 'admin', 'password')
while True:
device.monitor()
time.sleep(300)
device.close()
这个脚本通过使用 paramiko 库,建立 SSH 连接到交换机设备上,并执行从文件中读取的命令。在每次监控中,它会检查风扇状态并在需要时发出警告,同时在每天的午夜备份设备的配置文件。这个脚本还需要进一步修改和完善,以满足所有要求。
原文地址: https://www.cveoy.top/t/topic/ocxu 著作权归作者所有。请勿转载和采集!