batman.py 2.1 KB

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