forked from Hydrosys4/Master
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwpa_cli_mod.py
executable file
·321 lines (267 loc) · 7.64 KB
/
wpa_cli_mod.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
from __future__ import print_function
from __future__ import division
from past.utils import old_div
import logging
import time
import subprocess
logger = logging.getLogger("hydrosys4."+__name__)
def db2dbm(quality):
"""
Converts the Radio (Received) Signal Strength Indicator (in db) to a dBm
value. Please see http://stackoverflow.com/a/15798024/1013960
"""
dbm = int((old_div(quality, 2)) - 100)
return min(max(dbm, -100), -50)
"""
target is to implement the following:
wpa_cli status
wpa_cli scan
wpa_cli scan_results
wpa_cli list_network
"""
#SUPPLICANT_LOG_FILE = "wpa_supplicant.log"
def run_program(cmd):
"""
Runs a program, and it's paramters (e.g. rcmd="ls -lh /var/www")
Returns output if successful, or None and logs error if not.
"""
try:
#ifup_output = subprocess.check_output(cmd).decode('utf-8')
result=subprocess.run(cmd, capture_output="True", text="True")
ifup_output=result.stdout
#print(ifup_output)
return ifup_output
except subprocess.CalledProcessError as e:
print("Something wrong: ", e)
return "FAIL"
def wpa_terminate(_iface):
"""
Terminates any running wpa_supplicant process, and then starts a new one.
"""
cmd=['wpa_cli' , 'terminate']
run_program(cmd)
time.sleep(1)
def get_networks_old(iface, retry=1):
"""
Grab a list of wireless networks within range, and return a list of dicts describing them.
"""
while retry > 0:
output=run_program(['wpa_cli', '-i' + iface , 'scan'])
time.sleep(3)
if ("OK" in output.upper()):
networks=[]
lines = run_program(['wpa_cli', '-i' + iface , 'scan_result']).split("\n")
time.sleep(1.5)
if lines:
for line in lines[1:-1]:
#bssid / frequency / signal level / flags / ssid
if line:
linevect=line.split('\t')
if len(linevect)>4:
b, fr, s, f, ss = line.split('\t')[:5]
# according to the SSID naming, it is possible to have spaces in the SSID
# damn it
# SSID = final part of the line string, as separators "\t" seems to work
networks.append( {"bssid":b, "freq":fr, "sig":s, "ssid":ss, "flag":f} )
if networks:
return networks
retry-=1
logger.debug("Couldn't retrieve networks, retrying")
time.sleep(0.5)
logger.warning("Failed to list networks")
return []
def getbetweenquotes(text):
import re
matches=re.findall(r'\"(.+?)\"',text)
# matches is now ['String 1', 'String 2', 'String3']
if matches:
return matches[0]
else:
return ""
def get_networks(iface, retry=1):
"""
Grab a list of wireless networks within range
"""
cmd = ["sudo" , "iwlist", iface, "scan" ] #"scan | grep 'ESSID'"] # sudo is necessary
while retry > 0:
output=run_program(cmd)
if output:
networks=[]
for line in output.split("\n"):
#bssid / frequency / signal level / flags / ssid
if line:
if 'ESSID:' in line:
essid=getbetweenquotes(line)
networks.append( {"ssid":essid} )
if networks:
return networks
retry-=1
logger.debug("Couldn't retrieve networks, retrying")
time.sleep(0.5)
logger.warning("Failed to list networks")
return []
def remove_all(iface):
"""
Disconnect all wireless networks.
"""
cmd=['sudo','wpa_cli', '-i' + iface , 'list_networks']
lines = run_program(cmd).split("\n")
if lines:
for line in lines[1:-1]:
net_id=line.split()[0]
remove_network(iface,net_id)
def remove_network(iface,net_id):
cmd=['sudo','wpa_cli', '-i' + iface , 'remove_network' , net_id]
run_program(cmd)
def get_saved_networks(iface):
cmd=['sudo','wpa_cli', '-i' + iface , 'list_networks']
lines = run_program(cmd).split("\n")
networks=[]
if lines:
for line in lines[1:-1]:
datavect = line.split("\t") # do not use space as separator, the SSID can have spaces inside
if len(datavect)>1:
# network id / ssid / bssid / flags
networks.append( {"net_id":datavect[0], "ssid":datavect[1]} )
return networks
def get_net_id(iface,ssid):
# find net_id
networks=get_saved_networks(iface)
for item in networks:
if item["ssid"]==ssid:
net_id=item["net_id"]
print("Network ID of the SSID = ",ssid, " ID= ", net_id)
return net_id
return ""
def remove_network_ssid(iface,ssid):
# find net_id
net_id=get_net_id(iface,ssid)
if net_id:
print("net id to remove ", net_id)
remove_network(iface,net_id)
print("saved ", saveconfig(iface))
updateconfig(iface)
return True
return False
def disable_all(iface):
"""
Disable all wireless networks.
"""
cmd=['sudo','wpa_cli', '-i' + iface , 'list_networks']
lines = run_program(cmd).split("\n")
if lines:
for line in lines[1:-1]:
net_id=line.split()[0]
disable_network(iface,net_id)
return True
return False
def disable_network_ssid(iface,ssid):
if ssid=="":
return disable_all(iface)
else:
# find net_id
net_id=get_net_id(iface,ssid)
if net_id:
print("net id to disable ", net_id)
return disable_network(iface,net_id)
return False
def disable_network(iface,net_id):
cmd=['sudo','wpa_cli', '-i' + iface , 'disable_network' , net_id]
strout=run_program(cmd)
if not "OK" in strout:
return False
return True
def enable_network(iface,net_id):
cmd=['sudo','wpa_cli', '-i' + iface , 'enable_network' , net_id]
run_program(cmd)
def updateconfig(iface):
cmd=['sudo','wpa_cli', '-i' + iface ,'reconfigure']
run_program(cmd)
def saveconfig(iface):
cmd=['sudo','wpa_cli', '-i' + iface ,'save_config' ]
strout=run_program(cmd)
if not "OK" in strout:
return False
return True
def save_network(iface,ssid,password):
# if same SSID already present then remove it before saving
remove_network_ssid(iface,ssid)
cmd=['sudo','wpa_cli', '-i' + iface , 'add_network']
net_id=run_program(cmd)
print("Net ID to add " , net_id)
cmd=['sudo','wpa_cli', '-i' + iface , 'set_network', net_id , 'ssid' , '"'+ssid+'"' ]
strout=run_program(cmd)
print("ssid set " , strout)
if not "OK" in strout:
return False
cmd=['sudo','wpa_cli', '-i' + iface , 'set_network', net_id , 'psk' , '"'+password+'"' ]
strout=run_program(cmd)
print("ssid psk " , strout)
if not "OK" in strout:
return False
# enable network
#enable_network(iface,net_id)
# save config
if not saveconfig(iface):
return False
updateconfig(iface)
return True
def enable_ssid(iface, ssid):
cmd=['sudo' , 'wpa_cli', '-i' + iface , 'list_networks']
lines = run_program(cmd).split("\n")
if lines:
for line in lines[1:-1]:
strlist = line.split("\t") # do not use space as separator, the SSID can have spaces inside
if strlist:
net_id=strlist[0]
ssidout=strlist[1]
if ssid==ssidout:
enable_network(iface,net_id)
return True
return False
def listsavednetwork(iface):
#updateconfig(iface)
cmd=['sudo','wpa_cli', '-i' + iface , 'list_networks']
lines = run_program(cmd).split("\n")
data=[]
if lines:
for line in lines[1:-1]:
strlist = line.split("\t") # do not use space as separator, the SSID can have spaces inside
if len(strlist)>1:
net_id=strlist[0]
ssidout=strlist[1]
if ssidout!="":
data.append(ssidout)
return data
def status(iface):
"""
Check if we're associated to a network.
"""
cmd=['sudo','wpa_cli', '-i' + iface , 'status']
lines = run_program(cmd).split("\n")
if lines:
data=[]
for line in lines[1:-1]:
strlist = line.split("=")
if len(strlist)>1:
itemdict={}
itemdict[strlist[0]]=strlist[1]
data.append(itemdict)
return data
def has_ip(_iface):
"""
Check if we have an IP address assigned
"""
status = run_program("wpa_cli -i %s status" % _iface)
r = re.search("ip_address=(.*)", status)
if r:
return r.group(1)
return False
def do_dhcp(_iface):
"""
Request a DHCP lease.
"""
run_program("dhclient %s" % _iface)
if __name__ == "__main__":
network = get_networks("wlan0")
print(network)