华为5700交换机监控脚本:使用Python、paramiko、ncclient实现
-- 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', '
分析设备状态
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', '
保存配置文件并备份到电脑本地
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 = '''
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)
原文地址: https://www.cveoy.top/t/topic/n2d4 著作权归作者所有。请勿转载和采集!