如何在 python textfsm 中组合 2 个正则表达式?

How to combine 2 regular expression in python textfsm?

我有一个 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 模板中写一个正则表达式来获得接口 "lo" 和空白的 HWaddr?

^${接口}.*(HWaddr\s+${MAC}|环回)

是我的猜测。这会创建一个替代匹配字符串。 放入 regex101 https://regex101.com/r/lqzfFP/1