netmiko:无法执行列表中的命令

netmiko: can't execute commands from list

我通过字符串 cmd = 'show version | include IOS'

执行 Cisco 命令没问题
from netmiko import ConnectHandler

cisco_device = {
    'device_type': 'cisco_ios',
    'ip': 'Router1',
    'username': 'u',
    'password': 'p'
}

# string OK
cmd = 'show version | include IOS'
print(type(cmd))

net_connect = ConnectHandler(**cisco_device)
output = net_connect.send_command(cmd)
print(output)

输出

user@linux:~$ python script-str.py 
<class 'str'>
Cisco IOS Software, 3700 Software (C3725-ADVENTERPRISEK9-M), Version 12.4(15)T7, RELEASE SOFTWARE (fc3)
user@linux:~$ 

但是,当我将其更改为列表时,它不起作用。

from netmiko import ConnectHandler

cisco_device = {
    'device_type': 'cisco_ios',
    'ip': 'Router1',
    'username': 'u',
    'password': 'p'
}

# list problem
cmd = ['show version | include IOS']
print(type(cmd))

net_connect = ConnectHandler(**cisco_device)
output = net_connect.send_command(cmd)
print(output)

输出

user@linux:~$ python script-list.py
<class 'list'>
Traceback (most recent call last):
  File "script-list.py", line 14, in <module>
    output = net_connect.send_command(cmd)
  File "/home/user/.local/lib/python3.7/site-packages/netmiko/utilities.py", line 347, in wrapper_decorator
    return func(self, *args, **kwargs)
  File "/home/user/.local/lib/python3.7/site-packages/netmiko/base_connection.py", line 1378, in send_command
    command_string = self.normalize_cmd(command_string)
  File "/home/user/.local/lib/python3.7/site-packages/netmiko/base_connection.py", line 1532, in normalize_cmd
    command = command.rstrip()
AttributeError: 'list' object has no attribute 'rstrip'
user@linux:~$ 

第二个代码的 list 有什么问题,如何解决?

在您的脚本中 net_connect.send_command(cmd) 接受字符串作为参数并且您将列表传递给它。

在您的第二个示例中,尝试从列表 cmd[0] 发送字符串值,这是一个字符串。

from netmiko import ConnectHandler

cisco_device = {
    'device_type': 'cisco_ios',
    'ip': 'Router1',
    'username': 'u',
    'password': 'p'
}

# list problem
cmd = ['show version | include IOS']
print(type(cmd))

net_connect = ConnectHandler(**cisco_device)
output = net_connect.send_command(cmd[0])
print(output)

参考:https://github.com/ktbyers/netmiko/issues/167