I have a textfsm python code which parses "ifconfig" command in Linux terminal
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
In fsmcli.txt I have saved the "ifconfig" output
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)
And I have written the fsm template -fsm_cli.fsm as below
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
When I run the python file i get the below output:
['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']
I'm not able to parse the "lo" interface (you could see the empty string in the third line of output). I know the reason because I have used "^${Interface}.*HWaddr\s+${MAC}" in the fsm template. Since "lo" doesn't have Hwaddr it is not printing. But how could I write a regular expression in fsm template to get the interface "lo" with blank HWaddr for it?
^${Interface}.*(HWaddr\s+${MAC}|Loopback)
would be my guess. That creates an alternative matching string. put into regex101 https://regex101.com/r/lqzfFP/1