batman.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. from copy import deepcopy
  4. import io
  5. import json
  6. import socket
  7. import subprocess
  8. import time
  9. import string
  10. import StringIO
  11. class BatmanParser:
  12. batadv_vis = 'batadv-vis'
  13. mactranslation = string.maketrans('2367abef', '014589cd')
  14. def sanitycheck(self):
  15. testdata = None
  16. try:
  17. testdata = subprocess.check_output([self.batadv_vis, '-f', 'jsondoc'])
  18. except Exception as err:
  19. raise Exception("batadv-vis not found or incompatible: " + str(err))
  20. try:
  21. check = json.loads(testdata)
  22. except Exception as err:
  23. raise Exception("batadv-vis does not return valid JSON data: " + str(err))
  24. return True
  25. def mac2id(self, mac):
  26. temp = str(mac.lower().replace(':', ''))
  27. # temp = temp[0] + temp[1].translate(self.mactranslation) + temp[2:]
  28. return temp
  29. def fetch(self, batadv_dump=None, include_rawdata=False):
  30. data = { }
  31. ts = int(time.time())
  32. rawdata = subprocess.check_output([self.batadv_vis, '-f', 'jsondoc'])
  33. batmandata = json.loads(rawdata)
  34. if not batadv_dump is None:
  35. jsondata = json.dumps(batmandata, ensure_ascii=False)
  36. f = io.open(batadv_dump, 'w')
  37. f.write(rawdata)
  38. f.close()
  39. for item in batmandata['vis']:
  40. itemid = self.mac2id(item['primary'])
  41. aliases = []
  42. if 'secondary' in item:
  43. for mac in item['secondary']:
  44. aliases.append(self.mac2id(mac))
  45. neighbours = {}
  46. if 'neighbors' in item:
  47. for neighbour in item['neighbors']:
  48. if neighbour['router'] != item['primary']:
  49. #print('node {0}\'s neighbor {1} has unexpected router {2}'.format(itemid, neighbour['neighbor'], neighbour['router']))
  50. neighbours[self.mac2id(neighbour['neighbor'])] = float(neighbour['metric'])
  51. data[itemid] = {
  52. 'aliases': aliases,
  53. 'neighbours': neighbours,
  54. 'clients': [ self.mac2id(x) for x in item['clients'] ] if 'clients' in item else [],
  55. }
  56. return data
  57. if __name__ == "__main__":
  58. b = BatmanParser()
  59. try:
  60. b.sanitycheck()
  61. except Exception as err:
  62. print('SANITY-CHECK failed:', str(err))
  63. import sys
  64. sys.exit(1)
  65. data = b.fetch()
  66. print(json.dumps(data))