导入依赖库

import paramiko from ncclient import manager import time import datetime

定义一个华为交换机类

class HuaweiSwitch: def init(self, ip, username, password): self.ip = ip self.username = username self.password = password

# 连接SSH并返回连接对象
def connect_ssh(self):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(self.ip, username=self.username, password=self.password)
    return ssh

# 执行命令并返回结果
def exec_command(self, cmd):
    ssh = self.connect_ssh()
    stdin, stdout, stderr = ssh.exec_command(cmd)
    result = stdout.read().decode()
    ssh.close()
    return result

# 监控设备状态
def monitor_status(self):
    # 从命令文件中读取需要执行的命令
    with open('commands.txt', 'r') as f:
        commands = f.readlines()
    result = {}
    for cmd in commands:
        output = self.exec_command(cmd.strip())
        result[cmd.strip()] = output
    return result

# 检查风扇状态是否正常
def check_fan_status(self):
    result = self.monitor_status()
    fans = result['display device fan state']
    if 'normal' not in fans:
        print("All fans are faulty!")

# 备份配置文件
def backup_config(self):
    # 获取当前日期并格式化为指定格式
    date = datetime.datetime.now().strftime('%Y_%m_%d')
    filename = f"{date}_{self.ip}.zip"
    # 保存配置文件到设备端
    self.exec_command(f"save configuration to {filename}")
    # 通过SFTP将配置文件下载到本地
    with paramiko.Transport((self.ip, 22)) as transport:
        transport.connect(username=self.username, password=self.password)
        sftp = paramiko.SFTPClient.from_transport(transport)
        sftp.get(filename, f"local/{filename}")
        sftp.close()

# 配置日志主机
def configure_log_host(self):
    # 使用NETCONF连接设备
    with manager.connect(host=self.ip, username=self.username, password=self.password, 
                         hostkey_verify=False, device_params={'name': 'huawei'}) as m:
        # 打开NETCONF功能
        m.lock('running')
        m.edit_config(target='running', config='<netconf-yang xmlns="http://www.huawei.com/netconf/vrp" module="netconf"/>')
        m.unlock('running')
        # 配置日志主机为10.1.60.2
        config = '''
                 <config>
                   <logging xmlns="http://www.huawei.com/netconf/vrp">
                     <logHosts>
                       <logHost>
                         <hostIp>10.1.60.2</hostIp>
                       </logHost>
                     </logHosts>
                   </logging>
                 </config>
                 '''
        m.edit_config(target='running', config=config)

判断是否为主程序

if name == 'main': # 创建一个华为交换机对象 switch = HuaweiSwitch('10.1.1.1', 'admin', 'password') # 检查风扇状态 switch.check_fan_status() # 备份配置文件 switch.backup_config() # 配置日志主机 switch.configure_log_host(

对代码加以注释import paramikofrom ncclient import managerimport timeimport datetimeclass HuaweiSwitch def __init__self ip username password selfip = ip selfusername = username selfpas

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

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