华为设备

使用Python编写脚本并加上注释

使用ncclient、paramiko、time、datetime模块

输入display cpu

# 导入所需模块
import paramiko
from ncclient import manager
import time
import datetime

# 定义设备信息
device = {
    'ip': '10.1.1.1',
    'port': 22,
    'username': 'admin',
    'password': 'password',
}

# 定义命令
command = 'display cpu'

# 定义SSH连接函数
def ssh_connect(device):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=device['ip'], port=device['port'], username=device['username'], password=device['password'])
    return ssh

# 定义获取命令输出函数
def get_output(command):
    ssh = ssh_connect(device)
    stdin, stdout, stderr = ssh.exec_command(command)
    output = stdout.read().decode()
    ssh.close()
    return output

# 定义获取设备CPU利用率函数
def get_cpu():
    with manager.connect(host=device['ip'], port=device['port'], username=device['username'], password=device['password'], timeout=10, device_params={'name': 'huawei'}) as m:
        cpu_xml = '''
            <rpc>
                <exec command="display cpu"/>
            </rpc>
        '''
        result = m.dispatch(xml=cpu_xml).xml
        cpu = result.split('>')[2].split()[0]
        return cpu

# 获取当前时间
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

# 获取CPU利用率和命令输出
cpu = get_cpu()
output = get_output(command)

# 输出结果
print('当前时间:', now)
print('CPU利用率:', cpu)
print('命令输出:\n', output)
``
华为设备使用python写脚本并加上注释使用ncclientparamikotimedatetime输入display cpu

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

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