TextFSM - Parsing Issues

28 views Asked by At

I have some trouble with textFSM, and I don't know if I am doing it right:

So the output that i want to parse is this one:

snmp-server host 10.140.300.200 traps version 2c ldldo-1ldd
snmp-server host 10.140.300.200 use-vrf management
snmp-server host 10.132.300.101 traps version 2c oelee-doeoel
snmp-server host 10.132.300.101 use-vrf management
snmp-server host 10.132.300.101 source-interface kedl1
snmp-server host 10.151.230.230 traps version 2c SNMP1sAPain
snmp-server host 10.105.10.104 traps version 2c oelee-doeoel
snmp-server host 10.105.10.104 use-vrf management
snmp-server host 10.105.10.104 source-interface kedl1

And my template is:

Value host (\S+)
Value version (\S+)
Value community (\S+)
Value vrf (\S+)
Value source_interface (\S+)

Start
  ^snmp-server\s+host\s+${host}\s+traps\s+version\s+${version}\s+${community}
  ^snmp-server\s+host\s+${host}\s+use-vrf\s+${vrf}
  ^snmp-server\s+host\s+${host}\s+source-interface\s+${source_interface} -> Record

the output:

[{'host': '10.132.300.101',
  'version': '2c',
  'community': 'oelee-doeoel',
  'vrf': 'management',
  'source_interface': 'kedl1'},
 {'host': '10.105.10.104',
  'version': '2c',
  'community': 'oelee-doeoel',
  'vrf': 'management',
  'source_interface': 'kedl1'}

But with that template I only capture the output which mirror that.

How can I capture the others hosts: '10.140.300.200', '10.151.230.230'?

Thanks in advance

1

There are 1 answers

0
Tim Roberts On

Here's a simple solution without requiring any external modules:

import json

lastip = None
collection = []
for line in open('x.txt'):
    parts = line.rstrip().split()[2:]
    ip = parts.pop(0)
    verb = parts.pop(0)
    if ip != lastip:
        collection.append( {'host': ip} )
        lastip = ip
    if verb == 'traps':
        collection[-1]['version'] = parts[1]
        collection[-1]['community'] = parts[2]
    elif verb == 'use-vrf':
        collection[-1]['vrf'] = parts[0]
    elif verb == 'source-interface':
        collection[-1]['source_interface'] = parts[0]

print(json.dumps(collection,indent=4))

Output:

[
    {
        "host": "10.140.300.200",
        "version": "2c",
        "community": "ldldo-1ldd",
        "vrf": "management"
    },
    {
        "host": "10.132.300.101",
        "version": "2c",
        "community": "oelee-doeoel",
        "vrf": "management",
        "source_interface": "kedl1"
    },
    {
        "host": "10.151.230.230",
        "version": "2c",
        "community": "SNMP1sAPain"
    },
    {
        "host": "10.105.10.104",
        "version": "2c",
        "community": "oelee-doeoel",
        "vrf": "management",
        "source_interface": "kedl1"
    }
]