batman.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. """Checks that batadv-vis is executable and gives sane output."""
  18. testdata = None
  19. try:
  20. testdata = subprocess.check_output([self.batadv_vis, '-f', 'jsondoc'])
  21. except Exception as err:
  22. raise Exception("batadv-vis not found or incompatible: " + str(err))
  23. try:
  24. check = json.loads(testdata)
  25. except Exception as err:
  26. raise Exception("batadv-vis does not return valid JSON data: " + str(err))
  27. return True
  28. def mac2id(self, mac):
  29. """Derives a nodeid from the given MAC address."""
  30. temp = str(mac.lower().replace(':', ''))
  31. # temp = temp[0] + temp[1].translate(self.mactranslation) + temp[2:]
  32. return temp
  33. def fetch(self, batadv_dump=None, include_rawdata=False):
  34. """Fetches the current data from batadv-vis and returns it."""
  35. data = { }
  36. ts = int(time.time())
  37. # call batadv-vis and parse output as JSON
  38. rawdata = subprocess.check_output([self.batadv_vis, '-f', 'jsondoc'])
  39. batmandata = json.loads(rawdata)
  40. # dump raw data into file if requested
  41. if not batadv_dump is None:
  42. jsondata = json.dumps(batmandata, ensure_ascii=False)
  43. f = io.open(batadv_dump, 'w')
  44. f.write(rawdata)
  45. f.close()
  46. # parse raw data, convert all MAC into nodeid
  47. for item in batmandata['vis']:
  48. itemid = self.mac2id(item['primary'])
  49. aliases = []
  50. if 'secondary' in item:
  51. for mac in item['secondary']:
  52. aliases.append(self.mac2id(mac))
  53. neighbours = {}
  54. if 'neighbors' in item:
  55. for neighbour in item['neighbors']:
  56. #if neighbour['router'] != item['primary']:
  57. # print('node {0}\'s neighbor {1} has unexpected router {2}'.format(itemid, neighbour['neighbor'], neighbour['router']))
  58. neighbours[neighbour['neighbor']] = float(neighbour['metric'])
  59. # construct dict entry as expected by BATCAVE
  60. data[itemid] = {
  61. 'aliases': aliases,
  62. 'neighbours': neighbours,
  63. 'clients': [ x for x in item['clients'] ] if 'clients' in item else [],
  64. '__UPDATED__': { 'batadv': ts, },
  65. '__RAW__': { 'batadv': { itemid: item, } },
  66. }
  67. return data
  68. # standalone test mode
  69. if __name__ == "__main__":
  70. b = BatmanParser()
  71. try:
  72. b.sanitycheck()
  73. except Exception as err:
  74. print('SANITY-CHECK failed:', str(err))
  75. import sys
  76. sys.exit(1)
  77. data = b.fetch()
  78. print(json.dumps(data))