使用python写一个脚本加注释并生成log1 定期对X园区设备X_T1_ACC2的关键运行状态进行监控5min; 电源状态 display power 风扇状态 display fan LACP状态 display lacp statistics eth-trunk CPU、内存利用率 cpu-usage memory-usage OSPF邻居状态 display os
注:本脚本为示例代码,仅供参考,具体实现方式可能因环境和需求不同而有所区别。
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}:\n{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}\n")
if name == "main": switch = Switch("X_T1_ACC2", "192.168.0.1", "username", "password") switch.monitor(
原文地址: https://www.cveoy.top/t/topic/fl5D 著作权归作者所有。请勿转载和采集!