comparison service/wifi/wifi.py @ 1223:34de6cfa0b6b

rename historical 'tomatoWifi' Ignore-this: 8a3f1f261df50e8029cf9de5b11a6896 darcs-hash:1b2345513349fd24e5b3992141f0b0f72ad43910
author drewp <drewp@bigasterisk.com>
date Sat, 30 Mar 2019 16:58:08 -0700
parents
children e1202af42d4d
comparison
equal deleted inserted replaced
1222:4ae655806141 1223:34de6cfa0b6b
1 import re, ast, logging, socket, json
2 import lxml.html.soupparser
3 from twisted.internet.defer import inlineCallbacks, returnValue
4 from cyclone.httpclient import fetch
5 from rdflib import Literal, Graph, RDFS, URIRef
6
7 log = logging.getLogger()
8
9 class Router(object):
10 def __repr__(self):
11 return repr(self.__dict__)
12
13 class Wifi(object):
14 """
15 gather the users of wifi from the tomato routers
16 """
17 def __init__(self, accessN3="/my/proj/openid_proxy/access.n3"):
18 self.rereadConfig()
19 #self._loadRouters(accessN3, tomatoUrl)
20
21 def rereadConfig(self):
22 self.graph = Graph()
23 self.graph.parse('config.n3', format='n3')
24
25
26 def _loadRouters(self, accessN3, tomatoUrl):
27 g = Graph()
28 g.parse(accessN3, format="n3")
29 repl = {
30 '/wifiRouter1/' : None,
31 #'/tomato2/' : None
32 }
33 for k in repl:
34 rows = list(g.query('''
35 PREFIX p: <http://bigasterisk.com/openid_proxy#>
36 SELECT ?prefix WHERE {
37 ?site
38 p:requestPrefix ?public;
39 p:proxyUrlPrefix ?prefix
40 .
41 }''', initBindings={"public" : Literal(k)}))
42 repl[k] = str(rows[0][0])
43 log.debug('repl %r', repl)
44
45 self.routers = []
46 for url in tomatoUrl:
47 name = url
48 for k, v in repl.items():
49 url = url.replace(k, v)
50
51 r = Router()
52 http, tail = url.split('//', 1)
53 userPass, tail = tail.split("@", 1)
54 r.url = http + '//' + tail
55 r.headers = {'Authorization': ['Basic %s' % userPass.encode('base64').strip()]}
56 r.name = {'wifiRouter1' : 'bigasterisk5',
57 'tomato2' : 'bigasterisk4'}[name.split('/')[1]]
58 self.routers.append(r)
59
60 @inlineCallbacks
61 def getPresentMacAddrs(self):
62 self.rereadConfig()
63 rows = yield loadOrbiData()
64 for row in rows:
65 if 'clientHostname' in row:
66 row['name'] = row['clientHostname']
67 mac = URIRef('http://bigasterisk.com/mac/%s' % row['mac'].lower())
68 label = self.graph.value(mac, RDFS.label)
69 if label:
70 row['name'] = label
71 returnValue(rows)
72
73 @inlineCallbacks
74 def getPresentMacAddrs_multirouter(self):
75 rows = []
76
77 for router in self.routers:
78 log.debug("GET %s", router)
79 try:
80 resp = yield fetch(router.url, headers=router.headers,
81 timeout=2)
82 except socket.error:
83 log.warn("get on %s failed" % router)
84 continue
85 data = resp.body
86 if 'Wireless -- Authenticated Stations' in data:
87 # zyxel 'Station Info' page
88 rows.extend(self._parseZyxel(data, router.name))
89 else:
90 # tomato page
91 rows.extend(self._parseTomato(data, router.name))
92
93 for r in rows:
94 try:
95 r['name'] = self.knownMacAddr[r['mac']]
96 except KeyError:
97 pass
98
99 returnValue(rows)
100
101 def _parseZyxel(self, data, routerName):
102 root = lxml.html.soupparser.fromstring(data)
103 for tr in root.cssselect('tr'):
104 mac, assoc, uth, ssid, iface = [td.text_content().strip() for td in tr.getchildren()]
105 if mac == "MAC":
106 continue
107 assoc = assoc.lower() == 'yes'
108 yield dict(router=routerName, mac=mac, assoc=assoc, connected=assoc)
109
110 def _parseTomato(self, data, routerName):
111 for iface, mac, signal in jsValue(data, 'wldev'):
112 yield dict(router=routerName, mac=mac, signal=signal, connected=bool(signal))
113
114
115 @inlineCallbacks
116 def loadUvaData():
117 config = json.load(open("priv-uva.json"))
118 headers = {'Authorization': ['Basic %s' % config['userPass'].encode('base64').strip()]}
119 resp = yield fetch('http://10.2.0.2/wlstationlist.cmd', headers=headers)
120 root = lxml.html.soupparser.fromstring(resp.body)
121 byMac = {}
122 for tr in root.cssselect('tr'):
123 mac, connected, auth, ssid, iface = [td.text_content().strip() for td in tr.getchildren()]
124 if mac == "MAC":
125 continue
126 connected = connected.lower() == 'yes'
127 byMac[mac] = dict(mac=mac, connected=connected, auth=auth == 'Yes', ssid=ssid, iface=iface)
128
129 resp = yield fetch('http://10.2.0.2/DHCPTable.asp', headers=headers)
130 for row in re.findall(r'new AAA\((.*)\)', resp.body):
131 clientHostname, ipaddr, mac, expires, iface = [s.strip("'") for s in row.rsplit(',', 4)]
132 if clientHostname == 'wlanadv.none':
133 continue
134 byMac.setdefault(mac, {}).update(dict(
135 clientHostname=clientHostname, connection=iface, ipaddr=ipaddr, dhcpExpires=expires))
136
137 returnValue(sorted(byMac.values()))
138
139 @inlineCallbacks
140 def loadCiscoData():
141 config = json.load(open("priv-uva.json"))
142 headers = {'Authorization': ['Basic %s' % config['userPass'].encode('base64').strip()]}
143 print headers
144 resp = yield fetch('http://10.2.0.2/', headers=headers)
145 print resp.body
146 returnValue([])
147
148 @inlineCallbacks
149 def loadOrbiData():
150 config = json.load(open("priv-uva.json"))
151 headers = {'Authorization': ['Basic %s' % config['userPass'].encode('base64').strip()]}
152 resp = yield fetch('http://orbi.bigasterisk.com/DEV_device_info.htm', headers=headers)
153
154 if not resp.body.startswith(('device=', 'device_changed=0\ndevice=', 'device_changed=1\ndevice=')):
155 raise ValueError(resp.body)
156
157 ret = []
158 for row in json.loads(resp.body.split('device=', 1)[-1]):
159 ret.append(dict(
160 connected=True,
161 ipaddr=row['ip'],
162 mac=row['mac'].lower(),
163 contype=row['contype'],
164 model=row['model'],
165 clientHostname=row['name'] if row['name'] != 'Unknown' else None))
166 returnValue(ret)
167
168
169 def jsValue(js, variableName):
170 # using literal_eval instead of json parser to handle the trailing commas
171 val = re.search(variableName + r'\s*=\s*(.*?);', js, re.DOTALL).group(1)
172 return ast.literal_eval(val)