batman.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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[self.mac2id(neighbour['neighbor'])] = float(neighbour['metric'])
  59. # construct dict entry as expected by BATCAVE
  60. data[itemid] = {
  61. 'aliases': aliases,
  62. 'neighbours': neighbours,
  63. 'clients': [ self.mac2id(x) for x in item['clients'] ] if 'clients' in item else [],
  64. '__UPDATED__': { 'batadv': ts, },
  65. }
  66. return data
  67. # standalone test mode
  68. if __name__ == "__main__":
  69. b = BatmanParser()
  70. try:
  71. b.sanitycheck()
  72. except Exception as err:
  73. print('SANITY-CHECK failed:', str(err))
  74. import sys
  75. sys.exit(1)
  76. data = b.fetch()
  77. print(json.dumps(data))