#!/usr/bin/env python import sys import time import re import pprint BIRD_REGEXP = r"(.*) \[(.*)] \*? ?\((.*)\) \[(.*)\]" def parse_bird(stream): """Should take the output of "birdc 'show route primary'" as input. Returns a dictionary with all the information.""" d = dict() for l in stream.readlines()[1:]: #l = l.translate(l.maketrans("", "",'()[]*')) data = re.match(BIRD_REGEXP, l.strip()) try: data = data.groups() prefix = data[0].split()[0] d[prefix] = { "nexthop": data[0].split()[2], "iface": data[0].split()[4], "bgp_peer": data[1].split()[0], "up_since": data[1].split()[1], "localpref": int(data[2]), "origin_as": int(data[3][2:-1]), "last_updated": int(time.time()), "current": True, } except Exception as e: print("Unable to parse line '{}' : {}".format(l, e)) return d def update(db, new): """Modify db in place, updating it to reflect the new data from bird.""" for prefix in db: db[prefix]["current"] = False for prefix in new: new[prefix]["first_seen"] = db[prefix]["first_seen"] if prefix in db and "first_seen" in db[prefix] and isinstance(db[prefix]["first_seen"], int) else int(time.time()) db.update(new) if __name__ == '__main__': pprint.pprint(parse_bird(sys.stdin))