Python脚本监控华为交换机运行状态并自动备份配置
导入所需库
import paramiko from ncclient import manager import time import datetime
定义交换机类
class Switch: def init(self, ip, username, password): self.ip = ip self.username = username self.password = password self.connect()
# 建立安全连接
def connect(self):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(self.ip, username=self.username, password=self.password)
# 执行命令
def execute_command(self, command):
stdin, stdout, stderr = self.client.exec_command(command)
return stdout.read().decode('utf-8')
# 监控状态并输出结果
def monitor(self):
# 读取命令文件
with open('commands.txt') as f:
commands = f.readlines()
# 获取当前时间
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 监控关键运行状态
for command in commands:
result = self.execute_command(command)
if 'fan' in command and 'faulty' in result:
print(f'{now}: Fan status: faulty')
else:
print(f'{now}: {result}')
# 保存配置文件并传输
def backup_config(self):
# 获取当前时间
now = datetime.datetime.now()
if now.hour == 0 and now.minute == 0:
# 保存配置文件
self.execute_command('save configuration to backup.cfg')
# 传输配置文件
with manager.connect(host=self.ip, port=830, username=self.username, password=self.password, hostkey_verify=False) as m:
m.copy_config(source='running', target=f'/home/admin/backup/{now.strftime('%Y%m%d%H%M%S')}.cfg')
# 配置设备日志主机
def configure_logging(self):
with manager.connect(host=self.ip, port=830, username=self.username, password=self.password, hostkey_verify=False) as m:
# 配置设备日志主机
config = '''
<config>
<logging xmlns='http://www.huawei.com/netconf/vrp' content-version='1.0'>
<log-hosts>
<log-host>
<ip-address>10.1.60.2</ip-address>
</log-host>
</log-hosts>
</logging>
</config>
'''
m.edit_config(config, target='running')
定义主函数
def main(): # 创建交换机对象 switch = Switch('192.168.1.1', 'admin', 'password')
# 监控状态并输出结果
switch.monitor()
# 保存配置文件并传输
switch.backup_config()
# 配置设备日志主机
switch.configure_logging()
# 关闭连接
switch.client.close()
执行主函数
if name == 'main': main()
原文地址: https://www.cveoy.top/t/topic/n2fw 著作权归作者所有。请勿转载和采集!