我正在尝试使用某种 textfsm/tabulate 工具将一个键列表(即 python(show ip interfacebrief) 命令的 csv 输出)放入表中。我使用带有标题的表格来尝试将其放入表格中,但它看起来像下一节中的输出(图 1)。我期望一些带有标题
'intf', 'ipaddr', 'stats', 'proto'
的内容,并且每个相应的描述都列在它们下面。任何帮助都将是救星!
图1-输出
intf ipaddr
统计原型
{'intf': 'GigabitEthernet1/0/21', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/22', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/23', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/24', 'ipaddr': 'unassigned', 'status': 'up', 'proto': 'up'} {'intf': 'GigabitEthernet1/0/25', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'} {'intf': 'GigabitEthernet1/0/26', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'}
我的代码如下所示:
from netmiko import ConnectHandler
import pandas
import csv
from tabulate import tabulate
cisco1 = {
"device_type": "cisco_ios",
"host": "cisco",
"username": "cisco",
"password": "cisco",
}
command = "show ip interface brief"
with ConnectHandler(**cisco1) as net_connect:
output = net_connect.send_command(command, use_textfsm=True)
dataset = [output]
#df = pandas.DataFrame(output)
#df.to_csv('new.csv', index=True, header=True)
headers = ['intf', 'ipaddr', 'stats', 'proto']
print(tabulate(dataset, headers = headers))
期望: 我期望标题为“intf”、“ipaddr”、“stats”、“proto”,并且每个相应的描述都列在它们下面。
如果我理解你的意思,问题是如何将字典列表转换为表格格式......
from tabulate import tabulate
output = [{'intf': 'GigabitEthernet1/0/21', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'},
{'intf': 'GigabitEthernet1/0/22', 'ipaddr': 'unassigned', 'status': 'down', 'proto': 'down'}]
您必须首先将字典列表转换为列表列表。在 Python 中,有很多方法可以做到这一点……但这只是其中之一。
output_list_of_list = [ list(dict.values()) for dict in output]
现在您可以以表格格式查看...
headers = ['intf', 'ipaddr', 'stats', 'proto']
tabulated_table = tabulate(output_list_of_list, headers)
print(tabulated_table)