使用 Python 脚本监控网络设备状态并生成日志
使用 Python 脚本监控网络设备状态并生成日志
本文介绍如何使用 Python 编写脚本监控网络设备的关键运行状态,包括电源、风扇、LACP、CPU 和内存利用率以及 OSPF 邻居状态。脚本将定期执行监控命令,并将结果记录到日志文件中。此外,脚本还实现了安全配置备份功能,定期将设备配置文件备份到本地电脑。
1. 定期监控设备状态
脚本会定期(每 5 分钟)对 X 园区设备 X_T1_ACC2 的以下关键运行状态进行监控:
- 电源状态 (display power)
- 风扇状态 (display fan)
- LACP 状态 (display lacp statistics eth-trunk)
- CPU、内存利用率 (cpu-usage memory-usage)
- OSPF 邻居状态 (display ospf peer brief)
2. 安全管理连接
脚本与交换机之间应建立安全的管理连接,使用 SSH 协议并配置强密码。
3. 状态监控结果分析
脚本会分析监控结果,并在风扇出现异常状态时(两个风扇状态全部为非 normal)给出明确提示:'All fans are faulty!'。
4. 命令加载机制
监控相关命令不会直接硬编码在代码中,而是以文件的形式保存(例如 X_T1_ACC2_commands.txt)。脚本从文件中读取命令并执行,方便修改和维护。
5. 配置文件备份
脚本每隔 24 小时备份一次 X_T1_ACC2 的配置文件,并通过安全的文件传输协议 (SFTP) 将配置文件备份在本地电脑。备份文件名为 '当天日期_设备名称',例如:2022_07_20_X_T1_ACC2.zip。
6. 代码结构和复用性
脚本采用类和函数来构建功能,提高代码的可读性和复用性。
代码示例
import paramiko
import ncclient
import time
import datetime
class Switch:
def __init__(self, name, ip, username, password):
self.name = name
self.ip = ip
self.username = username
self.password = password
self.logfile = f'{self.name}_log.txt'
self.commands_file = f'{self.name}_commands.txt'
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.connect()
def connect(self):
try:
self.client.connect(self.ip, username=self.username, password=self.password)
self.log('Connected to switch.')
except Exception as e:
self.log(f'Failed to connect to switch: {e}')
raise e
def disconnect(self):
self.client.close()
self.log('Disconnected from switch.')
def execute_command(self, command):
try:
stdin, stdout, stderr = self.client.exec_command(command)
output = stdout.read().decode()
error = stderr.read().decode()
if error:
self.log(f'Error executing command '{command}': {error}')
return output
except Exception as e:
self.log(f'Error executing command '{command}': {e}')
raise e
def monitor(self):
commands = self.load_commands()
while True:
try:
for command in commands:
output = self.execute_command(command)
self.log(f'{command}:
{output}')
if 'fan' in command and 'normal' not in output:
self.log('All fans are faulty!')
except Exception as e:
self.log(f'Error monitoring switch: {e}')
time.sleep(300)
def backup_config(self):
timestamp = datetime.datetime.now().strftime('%Y_%m_%d')
filename = f'{timestamp}_{self.name}.zip'
try:
with paramiko.Transport((self.ip, 22)) as transport:
transport.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(f'{self.name}.cfg', filename)
sftp.close()
self.log(f'Backed up config to {filename}.')
except Exception as e:
self.log(f'Failed to backup config: {e}')
raise e
def load_commands(self):
try:
with open(self.commands_file, 'r') as f:
commands = f.readlines()
return [c.strip() for c in commands]
except Exception as e:
self.log(f'Failed to load commands from file '{self.commands_file}': {e}')
raise e
def log(self, message):
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(self.logfile, 'a') as f:
f.write(f'{timestamp}: {message}
')
if __name__ == '__main__':
switch = Switch('X_T1_ACC2', '192.168.0.1', 'username', 'password')
switch.monitor()
注: 本脚本为示例代码,仅供参考,具体实现方式可能因环境和需求不同而有所区别。
运行环境和所需库
- Python 编译环境
- paramiko 库
- ncclient 库
- time 库
- datetime 库
原文地址: https://www.cveoy.top/t/topic/ocxD 著作权归作者所有。请勿转载和采集!