ffmap-backend/lib/batman.py

99 lines
2.8 KiB
Python
Raw Normal View History

import subprocess
import json
import re
2015-03-24 16:49:37 +01:00
class Batman(object):
"""
Bindings for B.A.T.M.A.N. Advanced
commandline interface "batctl"
"""
def __init__(self, mesh_interface='bat0'):
self.mesh_interface = mesh_interface
2015-03-24 16:49:37 +01:00
def vis_data(self, batadv_vis=False):
vds = self.vis_data_batctl_legacy()
if batadv_vis:
vds += self.vis_data_batadv_vis()
return vds
2015-03-24 16:49:37 +01:00
@staticmethod
def vis_data_helper(lines):
vd_tmp = []
for line in lines:
try:
utf8_line = line.decode('utf-8')
vd_tmp.append(json.loads(utf8_line))
except UnicodeDecodeError:
pass
return vd_tmp
2015-03-24 16:49:37 +01:00
def vis_data_batctl_legacy(self):
"""
2015-03-24 17:41:02 +01:00
Parse "batctl -m <mesh_interface> vd json -n"
into an array of dictionaries.
2015-03-24 16:49:37 +01:00
"""
2015-03-24 17:41:02 +01:00
output = subprocess.check_output(
['batctl', '-m', self.mesh_interface, 'vd', 'json', '-n'])
2015-03-24 16:49:37 +01:00
lines = output.splitlines()
vds = self.vis_data_helper(lines)
return vds
2015-03-24 16:49:37 +01:00
def vis_data_batadv_vis(self):
"""
2015-03-24 17:41:02 +01:00
Parse "batadv-vis -i <mesh_interface> -f json"
into an array of dictionaries.
2015-03-24 16:49:37 +01:00
"""
2015-03-24 17:41:02 +01:00
output = subprocess.check_output(
['batadv-vis', '-i', self.mesh_interface, '-f', 'json'])
2015-03-24 16:49:37 +01:00
lines = output.splitlines()
return self.vis_data_helper(lines)
2014-09-21 22:18:31 +02:00
2015-03-24 16:49:37 +01:00
def gateway_list(self):
"""
2015-03-24 17:41:02 +01:00
Parse "batctl -m <mesh_interface> gwl -n"
into an array of dictionaries.
2015-03-24 16:49:37 +01:00
"""
2015-03-24 17:41:02 +01:00
output = subprocess.check_output(
['batctl', '-m', self.mesh_interface, 'gwl', '-n'])
2015-03-24 16:49:37 +01:00
output_utf8 = output.decode('utf-8')
lines = output_utf8.splitlines()
2014-09-21 22:18:31 +02:00
2015-03-24 17:41:02 +01:00
own_mac = re.match(r"^.*MainIF/MAC: [^/]+/([0-9a-f:]+).*$",
lines[0]).group(1)
2014-09-21 22:18:31 +02:00
2015-03-24 16:49:37 +01:00
gateways = []
gw_mode = self.gateway_mode()
if gw_mode['mode'] == 'server':
gateways.append(own_mac)
2014-09-21 22:18:31 +02:00
2015-03-24 16:49:37 +01:00
for line in lines:
gw_line = re.match(r"^(?:=>)? +([0-9a-f:]+) ", line)
if gw_line:
gateways.append(gw_line.group(1))
2015-03-24 16:49:37 +01:00
return gateways
def gateway_mode(self):
"""
Parse "batctl -m <mesh_interface> gw"
"""
2015-03-24 17:41:02 +01:00
output = subprocess.check_output(
['batctl', '-m', self.mesh_interface, 'gw'])
2015-03-24 16:49:37 +01:00
elements = output.decode("utf-8").split()
mode = elements[0]
if mode == 'server':
return {'mode': 'server',
'bandwidth': elements[3]}
else:
return {'mode': mode}
if __name__ == "__main__":
2015-03-24 16:49:37 +01:00
bc = Batman()
vd = bc.vis_data()
gw = bc.gateway_list()
for x in vd:
print(x)
print(gw)
print(bc.gateway_mode())