bird.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python
  2. import sys
  3. import time
  4. import re
  5. import pprint
  6. BIRD_REGEXP = r"(.*) \[(.*)] \*? ?\((.*)\) \[(.*)\]"
  7. def parse_bird(stream):
  8. """Should take the output of "birdc 'show route primary'" as input.
  9. Returns a dictionary with all the information."""
  10. d = dict()
  11. for l in stream.readlines()[1:]:
  12. #l = l.translate(l.maketrans("", "",'()[]*'))
  13. data = re.match(BIRD_REGEXP, l.strip())
  14. try:
  15. data = data.groups()
  16. prefix = data[0].split()[0]
  17. d[prefix] = {
  18. "nexthop": data[0].split()[2],
  19. "iface": data[0].split()[4],
  20. "bgp_peer": data[1].split()[0],
  21. "up_since": data[1].split()[1],
  22. "localpref": int(data[2]),
  23. "origin_as": int(data[3][2:-1]),
  24. "last_updated": int(time.time()),
  25. "current": True,
  26. }
  27. except Exception as e:
  28. print("Unable to parse line '{}' : {}".format(l, e))
  29. return d
  30. def update(db, new):
  31. """Modify db in place, updating it to reflect the new data from bird."""
  32. for prefix in db:
  33. db[prefix]["current"] = False
  34. for prefix in new:
  35. 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())
  36. db.update(new)
  37. if __name__ == '__main__':
  38. pprint.pprint(parse_bird(sys.stdin))