我正在尝试从网络交换机检索显示接口状态并放入Pandas中(我有其他计划将来使用该数据)。
当我登录到网络交换机并自己运行 cli 命令时,这是我得到的输出
港口 | 姓名 | 状态 | VLAN | 复式 | 速度 | 类型 |
---|---|---|---|---|---|---|
Fa0/1 | 电脑数据 | 已连接 | 1 | 满 | a-100 | 10/100BaseTX |
Fa0/2 | 电脑数据 | 未连接 | 1 | 汽车 | 汽车 | 10/100BaseTX |
Fa0/3 | 已禁用 | 1 | 汽车 | 汽车 | 10/100BaseTX | |
Fa0/4 | 已连接 | 1 | 满 | a-100 | 10/100BaseTX | |
Fa0/5 | 克罗诺斯 | 未连接 | 1 | 汽车 | 汽车 | 10/100BaseTX |
Fa0/6 | 克罗诺斯 | 未连接 | 1 | 汽车 | 汽车 | 10/100BaseTX |
但是,当在 python 中使用带有 netmiko 的命令并将输出用作 Pandas Dataframe 时,我遇到了两个问题。输出本身很好,但看起来像是化妆品或表格问题。
这是我从代码中得到的输出。我还将其放入下面的表格形式中,您可以看到两个表格之间存在一些差异。
港口 | 姓名 | 状态 | VLAN | 复式 | 速度 | 类型 |
---|---|---|---|---|---|---|
Fa0/1 | 电脑 | 数据 | 已连接 | 1 | 满 | a-100 |
Fa0/2 | 电脑 | 数据 | 未连接 | 1 | 汽车 | 汽车 |
Fa0/3 | 已禁用 | 1 | 汽车 | 汽车 | 10/100BaseTX | 南 |
Fa0/4 | 已连接 | 1 | 满 | a-100 | 10/100BaseTX | 南 |
Fa0/5 | 克罗诺斯 | 未连接 | 1 | 汽车 | 汽车 | 10/100BaseTX |
Fa0/6 | 克罗诺斯 | 未连接 | 1 | 汽车 | 汽车 | 10/100BaseTX |
这是我的代码
from netmiko import ConnectHandler
import pandas as pd
def get_ip_address():
ip_address_request = input("Please enter the IP address of the device: ")
return ip_address_request
ip_address = get_ip_address()
switch = {
"device_type":"cisco_ios",
"ip": ip_address,
'username': 'redacted',
'password': 'redacted',
}
net_connect = ConnectHandler(**switch)
prompt = net_connect.find_prompt()
hostname = prompt[:-1]
status = net_connect.send_command("Show interface status", use_textfsm=True)
net_connect.disconnect()
sum_status = []
lines = status.strip().split('\n')
headers = lines[0].split()
for line in lines[1:]:
values = line.split()
entry = {}
for i, header in enumerate(headers):
if i < len(values):
entry[header] = values[i]
sum_status.append(entry)
status_df = pd.DataFrame(sum_status)
status_df.reset_index(inplace=True, drop=True)
pd.set_option('display.max_colwidth', None)
status_df.loc[:, 'Name'] = status_df['Name'].fillna('')
print(status_df.to_string(index=False))
这个问题实际上与熊猫无关。问题是原始输入中可能存在空字段。所以这是不正确的:
for line in lines[1:]:
values = line.split()
# generates bad input if there are empty fields
# also generates bad input when a field contains a space
要解决此问题,您必须解析或检查输入(逐行)并确定是否有空字段。例如,如果“状态”始终为“禁用”或“已连接”,那么您可以将其用作锚点(以确定列位置)。