我有一个textfsm python代码,解析Linux终端中的“ifconfig”命令
import textfsm
f = open('/home/Projects/test_ra/fsm_cli.txt')
inp = f.read()
f.close()
temp = open('/home/Projects/test_ra/fsm_cli.fsm')
tab = textfsm.TextFSM(temp)
res = tab.ParseText(inp)
print tab.header
for row in res:
print row
在fsmcli.txt中我保存了“ifconfig”输出
eth0 Link encap:Ethernet HWaddr 48:4d:7e:9e:ab:b8
inet addr:172.23.100.200 Bcast:172.23.106.255 Mask:255.255.255.0
inet6 addr: fe80::4a4d:7eaa:feaa:4eb8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1461589 errors:0 dropped:0 overruns:0 frame:0
TX packets:1576996 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1650010954 (1.6 GB) TX bytes:1856124201 (1.8 GB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:11047 errors:0 dropped:0 overruns:0 frame:0
TX packets:11047 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:1567815 (1.5 MB) TX bytes:1567815 (1.5 MB)
vboxnet0 Link encap:Ethernet HWaddr 0a:aa:27:00:00:00
inet addr:192.168.40.1 Bcast:192.168.33.255 Mask:255.255.255.0
inet6 addr: fe80::800:27ff:fe00:0/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:260 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:51436 (51.4 KB)
我已经编写了fsm模板-fsm_cli.fsm,如下所示
Value Interface (\w+)
Value MAC (\S+)
Value Mask (\S+)
Value MTU (\d+)
Value IP (\S+)
Start
^${Interface}.*HWaddr\s+${MAC}
^\s+inet addr:${IP}.*Mask:${Mask}
^.*MTU:${MTU} -> Record
当我运行python文件时,我得到以下输出:
['Interface', 'MAC', 'Mask', 'MTU', 'IP']
['eth0', '48:4d:7e:9e:4e:b8', '255.255.255.0', '1500', '172.23.106.239']
['', '', '255.0.0.0', '65536', '127.0.0.1']
['vboxnet0', '0a:00:27:00:00:00', '255.255.255.0', '1500', '192.168.33.1']
我无法解析“lo”界面(您可以在输出的第三行看到空字符串)。我知道原因是因为我在fsm模板中使用了“^ $ {Interface}。* HWaddr \ s + $ {MAC}”。由于“lo”没有Hwaddr,因此不打印。 但是我怎样才能在fsm模板中编写一个正则表达式来获取带有空白HWaddr的接口“lo”呢?
答案 0 :(得分:1)
^ $ {Interface}。*(HWaddr \ s + $ {MAC} | Loopback)
是我的猜测。这会创建一个替代匹配字符串。 放入regex101 https://regex101.com/r/lqzfFP/1