我正在尝试看似简单的操作 - 使用简单的字符串函数解析Cisco路由器输出(例如' split')。但是,我一直收到索引超出范围的错误,并且没有看到原因。
以下是我的开始,简单" show ip int brief"输出:
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 unassigned YES NVRAM up up
GigabitEthernet0/0.50 10.78.1.205 YES NVRAM up up
GigabitEthernet0/1 10.233.112.17 YES NVRAM up up
GigabitEthernet0/2 10.233.112.41 YES NVRAM up up
GigabitEthernet0/3 10.233.112.50 YES NVRAM up up
Loopback0 10.233.112.130 YES NVRAM up up
Tunnel0 10.233.112.130 YES unset up up
sdf-a-wan-rt-02#exit
这是我试图反对它的代码:
links = []
lines = output.split('\n')
for item in lines:
fields = item.split()
interface = fields[0]
ipaddress = fields[1]
linkstate = fields[4]
prtcstate = fields[5]
links.append([interface,ipaddress,linkstate,prtcstate])
print links
这是我得到的错误:
Traceback (most recent call last):
File "C:\Users\dtruman\Documents\PROJECTS\DEVOPS - ITOC CoE\NETWORK AUTOMATION\parse_output.py", line 32, in <module>
ipaddress = fields[1]
IndexError:列表索引超出范围
答案 0 :(得分:0)
您基本上拥有它,但您需要添加一个完整性检查,以确保您获得的数据符合您的预期。我做这样的事情:
links = []
lines = output.split('\n')
for item in lines:
fields = item.split()
# make sure data is the proper length so you don't go out of bounds
if len(fields) != 6:
continue
interface = fields[0]
ipaddress = fields[1]
linkstate = fields[4]
prtcstate = fields[5]
links.append([interface,ipaddress,linkstate,prtcstate])
print links
还有其他方法可以做到这一点,但这是我能想到的第一个方法。这可以确保在填写任何数据之前,为该行填充表中的所有6列。