华为设备监控脚本 - 使用 Python、ncclient、paramiko 和 NETCONF
导入必要的库
from ncclient import manager import paramiko import time import datetime
定义设备信息
device_ip = '192.168.1.1' device_username = 'admin' device_password = 'password' device_port = 22
定义执行命令函数
def execute_command(command): # 建立 SSH 连接 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(device_ip, port=device_port, username=device_username, password=device_password)
# 执行命令
stdin, stdout, stderr = ssh.exec_command(command)
output = stdout.read().decode('utf-8')
# 关闭 SSH 连接
ssh.close()
return output
定义获取当前时间函数
def get_current_time(): now = datetime.datetime.now() return now.strftime('%Y-%m-%d %H:%M:%S')
读取命令文件
with open('commands.txt', 'r') as f: commands = f.readlines()
去除命令中的空格和换行符
commands = [command.strip() for command in commands]
建立 NETCONF 连接
with manager.connect(host=device_ip, port=device_port, username=device_username, password=device_password, hostkey_verify=False, device_params={'name': 'huawei'}) as m:
# 循环执行命令
for command in commands:
# 使用 paramiko 执行命令
output = execute_command(command)
# 使用 NETCONF 发送命令
rpc_reply = m.dispatch(command)
# 打印执行结果和时间戳
print(f'Command: {command}')
print(f'Time: {get_current_time()}')
print(f'Output: {output}')
print(f'NETCONF Reply: {rpc_reply}
')
# 等待 5 秒钟
time.sleep(5)
原文地址: https://www.cveoy.top/t/topic/n39Y 著作权归作者所有。请勿转载和采集!