-- coding: utf-8 --

import paramiko from ncclient import manager import time import datetime

读取命令文件并执行

def execute_commands(ip, username, password, command_file): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password) with open(command_file, 'r') as f: commands = f.readlines() for command in commands: stdin, stdout, stderr = ssh.exec_command(command) print(stdout.read().decode()) ssh.close()

获取设备关键运行状态

def get_device_state(ip, username, password): with manager.connect(host=ip, port=830, username=username, password=password, hostkey_verify=False, device_params={'name': 'huawei'}) as m: print('设备电源状态') response = m.get(('subtree', '')) print(response.data_xml) print('设备风扇状态') response = m.get(('subtree', '')) print(response.data_xml) print('设备LACP状态') response = m.get(('subtree', '')) print(response.data_xml) print('设备CPU利用率') response = m.get(('subtree', '')) print(response.data_xml) print('设备内存利用率') response = m.get(('subtree', '')) print(response.data_xml) print('设备OSPF邻居状态') response = m.get(('subtree', '')) print(response.data_xml)

分析设备状态

def analyze_device_state(ip, username, password): with manager.connect(host=ip, port=830, username=username, password=password, hostkey_verify=False, device_params={'name': 'huawei'}) as m: response = m.get(('subtree', '')) fan_status = response.data_xml if 'faulty' in fan_status: print('风扇异常')

保存配置文件并备份到电脑本地

def backup_config(ip, username, password): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password) stdin, stdout, stderr = ssh.exec_command('save') print(stdout.read().decode()) ssh.close() transport = paramiko.Transport((ip, 22)) transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) filename = datetime.datetime.now().strftime('%Y-%m-%d') + '.cfg' sftp.get('/flash/'+filename, 'backup/'+filename) sftp.close() transport.close()

配置设备日志主机

def config_logging(ip, username, password): with manager.connect(host=ip, port=830, username=username, password=password, hostkey_verify=False, device_params={'name': 'huawei'}) as m: confstr = ''' 10.1.60.2 enable all ''' m.edit_config(target='running', config=confstr)

if name == 'main': ip = '192.168.1.1' username = 'admin' password = 'admin123' command_file = 'commands.txt' execute_commands(ip, username, password, command_file) get_device_state(ip, username, password) analyze_device_state(ip, username, password) now_time = datetime.datetime.now().strftime('%H:%M') if now_time == '00:00': backup_config(ip, username, password) config_logging(ip, username, password)

华为5700交换机监控脚本:使用Python、paramiko、ncclient实现

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

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