使用python写脚本加注释1 所执行的监控相关命令不在代码中固定以文件的形式保存脚本从文件中读取命令并执行2代码有层级结构复用率简单易读用类、函数来构建功能编写脚本用到paramiko、ncclient、time、datetime4个库3 每5分钟对设备的关键运行状态进行监控使用display电源风扇LACPCPU内存利用率OSPF邻居状态并输出结果4 与交换机建立安全连接5 对状态监控结果分析
-- coding: utf-8 --
import paramiko from ncclient import manager import time from datetime import datetime
class Switch: def init(self, ip, username, password): self.ip = ip self.username = username self.password = password
def connect(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 execute_command(self, command):
ssh = self.connect()
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode()
ssh.close()
return output
def check_fan_status(self):
fan_status = self.execute_command('display fan')
if 'Faulty' in fan_status:
print('Fan status: faulty')
else:
print('Fan status: normal')
def check_power_status(self):
power_status = self.execute_command('display power')
if 'Faulty' in power_status:
print('Power status: faulty')
else:
print('Power status: normal')
def check_lacp_status(self):
lacp_status = self.execute_command('display lacp')
if 'Down' in lacp_status:
print('LACP status: faulty')
else:
print('LACP status: normal')
def check_cpu_usage(self):
cpu_usage = self.execute_command('display cpu')
if '100%' in cpu_usage:
print('CPU usage: high')
else:
print('CPU usage: normal')
def check_mem_usage(self):
mem_usage = self.execute_command('display memory')
if '100%' in mem_usage:
print('Memory usage: high')
else:
print('Memory usage: normal')
def check_ospf_status(self):
ospf_status = self.execute_command('display ospf neighbor')
if 'FULL' not in ospf_status:
print('OSPF status: faulty')
else:
print('OSPF status: normal')
def check_status(self):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
self.check_fan_status()
self.check_power_status()
self.check_lacp_status()
self.check_cpu_usage()
self.check_mem_usage()
self.check_ospf_status()
def backup_config(self):
ssh = self.connect()
sftp = ssh.open_sftp()
sftp.put('current_config.txt', '/backup/current_config.txt')
sftp.close()
ssh.close()
def configure_netconf(self):
with manager.connect(host=self.ip,
username=self.username,
password=self.password,
hostkey_verify=False) as m:
nc_config = '''
<config>
<system>
<log>
<host>
<name>10.1.60.2</name>
</host>
</log>
</system>
</config>
'''
m.edit_config(target='running', config=nc_config)
if name == 'main': switch = Switch('192.168.1.1', 'admin', 'password') switch.check_status() switch.backup_config() switch.configure_netconf(
原文地址: https://www.cveoy.top/t/topic/e80y 著作权归作者所有。请勿转载和采集!