导入paramiko,ncclient,time,datetime模块

import paramiko import ncclient import time import datetime

定义Switch类

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")

如果运行的是当前文件,实例化Switch类,并调用monitor()方法

if name == "main": switch = Switch("X_T1_ACC2", "192.168.0.1", "username", "password") switch.monitor(

对下面的代码每一句都注释import paramikoimport ncclientimport timeimport datetimeclass Switch def __init__self name ip username password selfname = name selfip = ip selfusername = username

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

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