首页 > 解决方案 > 如何通过串行连接连接到 NetMiko?

问题描述

如何通过 NetMiko 上的串行总线连接?我知道3年前提出的这个问题。但是,它似乎不再相关。

我有以下代码。

from netmiko import ConnectHandler

device = {
    "device_type": "aruba_osswitch",
    "username": "manager",
    "password": "",
    "serial_settings": {"port": "COM4"}
}

net_connect = ConnectHandler(**device)

output = net_connect.send_command("show version")

print(output)

我收到错误:ValueError:必须设置 ip 或主机。但是,由于它是串行的,据我所知,它不需要主机或 IP。有人可以建议吗?

谢谢,

标签: pythonnetmiko

解决方案


我使用了以下代码片段: - https://semfionetworks.com/blog/establish-a-console-connection-within-a-python-script-with-pyserial/ 通过在 OpenSUSE OS 上稍作修改来实现这一点

$import serial
$from time import sleep


$def send_to_console(ser: serial.Serial, command: str, wait_time: float = 0.5):
     $command_to_send = command + "\r"
     $ser.write(command_to_send.encode('utf-8'))
     $sleep(wait_time)
     $print(ser.read(ser.inWaiting()). decode('utf-8'), end="") 

$with serial.Serial("/dev/ttyS8", timeout=1) as ser:
     $print(f"Connecting to {ser.name}...")
     $send_to_console(ser, "")
     $send_to_console(ser, "enable")
     $send_to_console(ser, "show ip interface brief", wait_time=2)
     $print(f"Connection to {ser.name} closed.")

推荐阅读