华为交换机监控脚本:使用 Python、paramiko、ncclient 实现安全监控和配置备份
导入必要的库
import paramiko from ncclient import manager import time import datetime
定义交换机IP地址、用户名、密码和端口号
host = '192.168.0.1' username = 'admin' password = 'password' port = 22
读取命令文件
with open('commands.txt', 'r') as f: commands = f.readlines()
建立SSH连接
ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=host, username=username, password=password, port=port)
定义函数执行命令并返回结果
def execute_command(command): stdin, stdout, stderr = ssh.exec_command(command) return stdout.readlines()
定义类保存交换机状态
class SwitchStatus(): def init(self): self.power = None self.fan = None self.lacp = None self.cpu = None self.memory = None self.ospf = None
def update(self):
# 执行命令并更新状态
self.power = execute_command('display power')
self.fan = execute_command('display fan')
self.lacp = execute_command('display lacp')
self.cpu = execute_command('display cpu')
self.memory = execute_command('display memory')
self.ospf = execute_command('display ospf neighbor')
def check_fan(self):
# 检查风扇状态
for line in self.fan:
if 'faulty' in line:
return 'faulty'
return 'normal'
定义函数执行NETCONF操作
def configure_netconf():
# 建立NETCONF连接
with manager.connect(host=host, port=830, username=username, password=password,
hostkey_verify=False, device_params={'name': 'huawei'}) as m:
# 配置设备日志主机
netconf_template = '''
定义函数备份配置文件
def backup_config(): # 建立SFTP连接 transport = ssh.get_transport() sftp = paramiko.SFTPClient.from_transport(transport) # 获取当前日期 today = datetime.datetime.now().strftime('%Y-%m-%d') # 备份配置文件 sftp.get('/config/config.cfg', f'{today}_config.cfg')
定义函数监控交换机状态并输出结果
def monitor_status(): # 创建SwitchStatus对象 switch = SwitchStatus() # 更新状态 switch.update() # 检查风扇状态 fan_status = switch.check_fan() # 输出结果 print(f'Power: {switch.power}') print(f'Fan: {fan_status}') print(f'LACP: {switch.lacp}') print(f'CPU: {switch.cpu}') print(f'Memory: {switch.memory}') print(f'OSPF: {switch.ospf}')
循环监控交换机状态
while True: monitor_status() # 每5分钟监控一次 time.sleep(300) # 每24h备份一次配置文件 if datetime.datetime.now().strftime('%H:%M') == '00:00': backup_config()
原文地址: https://www.cveoy.top/t/topic/n2fs 著作权归作者所有。请勿转载和采集!