Debian Codegraph @

plyer/platforms/linux/wifi.py

raw symbols SCIP
1 '''
2 .. note::
3 This facade depends on `nmcli` (Network Manager command line tool).
4 It's found in most of the popular GNU/Linux distributions. Support for other
5 backends is not provided yet.
6 '''
7
8 from subprocess import Popen, PIPE, call
9 from plyer.facades import Wifi
10 from plyer.utils import whereis_exe, deprecated
11
12 try:
13 import wifi
14 except ModuleNotFoundError as err:
15 raise ModuleNotFoundError(
16 "python-wifi not installed. try:" +
17 "`pip install --user wifi`.") from err
18
19
20 class NMCLIWifi(Wifi):
21 '''
22 .. versionadded:: 1.4.0
23 '''
24
25 def __init__(self, *args, **kwargs):
26 '''
27 .. versionadded:: 1.4.0
28 '''
29
30 super().__init__(*args, **kwargs)
31 self.names = {}
32
33 @property
34 def interfaces(self):
35 '''
36 Get all the available interfaces for WiFi.
37
38 .. versionadded:: 1.4.0
39 Tested with nmcli 1.2.6.
40 '''
41 if not self._is_enabled():
42 self._enable()
43
44 # fetch the devices
45 proc = Popen([
46 'nmcli', '--terse',
47 '--fields', 'DEVICE,TYPE',
48 'device'
49 ], stdout=PIPE)
50 lines = proc.communicate()[0].decode('utf-8').splitlines()
51
52 # filter devices by type
53 interfaces = []
54 for line in lines:
55 # bad escape from nmcli's side :<
56 line = line.replace('\\:', '$$')
57 device, dtype = line.split(':')
58 if dtype != 'wifi':
59 continue
60 interfaces.append(device.replace('$$', ':'))
61
62 # return wifi interfaces
63 return interfaces
64
65 def _is_enabled(self):
66 '''
67 Return the status of WiFi device.
68
69 .. versionadded:: 1.4.0
70 Tested with nmcli 1.2.6.
71 '''
72 output = Popen(
73 ["nmcli", "radio", "wifi"],
74 stdout=PIPE
75 ).communicate()[0].decode('utf-8')
76
77 if output.split()[0] == 'enabled':
78 return True
79 return False
80
81 def _is_connected(self, interface=None):
82 '''
83 Return whether a specified interface is connected to a WiFi network.
84
85 .. versionadded:: 1.4.0
86 Tested with nmcli 1.2.6.
87 '''
88 if not self._is_enabled():
89 self._enable()
90 if not interface:
91 interface = self.interfaces[0]
92
93 # fetch all devices
94 proc = Popen([
95 'nmcli', '--terse',
96 '--fields', 'DEVICE,TYPE,STATE',
97 'device'
98 ], stdout=PIPE)
99 lines = proc.communicate()[0].decode('utf-8').splitlines()
100
101 # filter by wifi type and interface
102 connected = False
103 for line in lines:
104 line = line.replace('\\:', '$$')
105 device, dtype, state = line.split(':')
106 device = device.replace('$$', ':')
107 if dtype != 'wifi':
108 continue
109
110 if device != interface:
111 continue
112
113 if state == 'connected':
114 connected = True
115
116 return connected
117
118 def _start_scanning(self, interface=None):
119 '''
120 Start scanning for available Wi-Fi networks
121 for the specified interface.
122
123 .. versionadded:: 1.4.0
124 Tested with nmcli 1.2.6.
125 '''
126 if not self._is_enabled():
127 self._enable()
128 if not interface:
129 interface = self.interfaces[0]
130
131 # force rescan for fresh data
132 call(['nmcli', 'device', 'wifi', 'rescan', 'ifname', interface])
133
134 # get properties
135 fields = [
136 'SSID', 'BSSID', 'MODE', 'CHAN', 'FREQ',
137 'BARS', 'RATE', 'SIGNAL', 'SECURITY'
138 ]
139
140 # fetch all networks for interface
141 output = Popen([
142 'nmcli', '--terse',
143 '--fields', ','.join(fields),
144 'device', 'wifi', 'list', 'ifname', interface
145 ], stdout=PIPE).communicate()[0].decode('utf-8')
146
147 # parse output
148 for line in output.splitlines():
149 line = line.replace('\\:', '$$')
150 row = {
151 field: value
152 for field, value in zip(fields, line.split(':'))
153 }
154
155 row['BSSID'] = row['BSSID'].replace('$$', ':')
156 self.names[row['SSID']] = row
157
158 def _get_network_info(self, name):
159 '''
160 Get all the network information by network's name (SSID).
161
162 .. versionadded:: 1.4.0
163 Tested with nmcli 1.2.6.
164 '''
165 if not self.names:
166 self._start_scanning()
167
168 ret_list = {}
169 ret_list['ssid'] = self.names[name]['SSID']
170 ret_list['signal'] = self.names[name]['SIGNAL']
171
172 bars = len(self.names[name]['BARS'])
173 ret_list['quality'] = '{}/100'.format(bars / 5.0 * 100)
174 ret_list['frequency'] = self.names[name]['FREQ']
175 ret_list['bitrates'] = self.names[name]['RATE']
176
177 # wpa1, wpa2, wpa1 wpa2, wep, (none), perhaps something else
178 security = self.names[name]['SECURITY'].lower()
179 ret_list['encrypted'] = True
180 if 'wpa2' in security:
181 # wpa2, wpa2+wpa1
182 ret_list['encryption_type'] = 'wpa2'
183 elif 'wpa' in security:
184 ret_list['encryption_type'] = 'wpa'
185 elif 'wep' in security:
186 ret_list['encryption_type'] = 'wep'
187 elif 'none' in security:
188 ret_list['encrypted'] = False
189 ret_list['encryption_type'] = 'none'
190 else:
191 ret_list['encryption_type'] = security
192
193 ret_list['channel'] = int(self.names[name]['CHAN'])
194 ret_list['address'] = self.names[name]['BSSID']
195 ret_list['mode'] = self.names[name]['MODE']
196 return ret_list
197
198 def _get_available_wifi(self):
199 '''
200 Return the names of all found networks.
201
202 .. versionadded:: 1.4.0
203 Tested with nmcli 1.2.6.
204 '''
205 if not self.names:
206 self._start_scanning()
207 return list(self.names.keys())
208
209 def _connect(self, network, parameters, interface=None):
210 '''
211 Connect a specific interface to a WiFi network.
212
213 Expects 2 parameters:
214 - SSID of the network
215 - parameters: dict
216 - password: string or None
217
218 .. versionadded:: 1.4.0
219 Tested with nmcli 1.2.6.
220 '''
221 self._enable()
222 if not interface:
223 interface = self.interfaces[0]
224
225 password = parameters.get('password')
226 command = [
227 'nmcli', 'device', 'wifi', 'connect', network,
228 'ifname', interface
229 ]
230 if password:
231 command += ['password', password]
232 call(command)
233
234 def _disconnect(self, interface=None):
235 '''
236 Disconnect a specific interface from a WiFi network.
237
238 .. versionadded:: 1.4.0
239 Tested with nmcli 1.2.6.
240 '''
241 if not self._is_enabled():
242 return
243
244 if not interface:
245 interface = self.interfaces[0]
246
247 if self._nmcli_version() >= (1, 2, 6):
248 call(['nmcli', 'device', 'disconnect', interface])
249 else:
250 call(['nmcli', 'nm', 'enable', 'false'])
251
252 def _enable(self):
253 '''
254 Turn WiFi device on.
255
256 .. versionadded:: 1.4.0
257 Tested with nmcli 1.2.6.
258 '''
259 call(['nmcli', 'radio', 'wifi', 'on'])
260
261 def _disable(self):
262 '''
263 Turn WiFi device off.
264
265 .. versionadded:: 1.4.0
266 Tested with nmcli 1.2.6.
267 '''
268 call(['nmcli', 'radio', 'wifi', 'off'])
269
270 def _nmcli_version(self):
271 '''
272 Get nmcli version to prevent executing deprecated commands.
273
274 .. versionadded:: 1.4.0
275 Tested with nmcli 1.2.6.
276 '''
277 version = Popen(['nmcli', '-v'], stdout=PIPE)
278 version = version.communicate()[0].decode('utf-8')
279 while version and not version[0].isdigit():
280 version = version[1:]
281 return tuple(map(int, (version.split('.'))))
282
283
284 @deprecated
285 class LinuxWifi(Wifi):
286 '''
287 .. versionadded:: 1.2.5
288 '''
289
290 def __init__(self, *args, **kwargs):
291 '''
292 .. versionadded:: 1.4.0
293 '''
294
295 super().__init__(*args, **kwargs)
296 self.names = {}
297
298 @property
299 def interfaces(self):
300 '''
301 .. versionadded:: 1.4.0
302 '''
303
304 proc = Popen([
305 'nmcli', '--terse',
306 '--fields', 'DEVICE,TYPE',
307 'device'
308 ], stdout=PIPE)
309 lines = proc.communicate()[0].decode('utf-8').splitlines()
310
311 interfaces = []
312 for line in lines:
313 device, dtype = line.split(':')
314 if dtype != 'wifi':
315 continue
316 interfaces.append(device)
317
318 return interfaces
319
320 def _is_enabled(self):
321 '''
322 Returns `True` if wifi is enabled else `False`.
323
324 .. versionadded:: 1.2.5
325 .. versionchanged:: 1.3.2
326 nmcli output is properly decoded to unicode
327 '''
328 enbl = Popen(["nmcli", "radio", "wifi"], stdout=PIPE, stderr=PIPE)
329 if enbl.communicate()[0].split()[0].decode('utf-8') == "enabled":
330 return True
331 return False
332
333 def _is_connected(self, interface=None):
334 '''
335 .. versionadded:: 1.4.0
336 '''
337
338 if not interface:
339 interface = self.interfaces[0]
340
341 proc = Popen([
342 'nmcli', '--terse',
343 '--fields', 'DEVICE,TYPE,STATE',
344 'device'
345 ], stdout=PIPE)
346 lines = proc.communicate()[0].decode('utf-8').splitlines()
347
348 connected = False
349 for line in lines:
350 device, dtype, state = line.split(':')
351 if dtype != 'wifi':
352 continue
353
354 if device != interface:
355 continue
356
357 if state == 'connected':
358 connected = True
359
360 return connected
361
362 def _start_scanning(self, interface=None):
363 '''
364 Returns all the network information.
365
366 .. versionadded:: 1.2.5
367 .. versionchanged:: 1.3.0
368 scan only if wifi is enabled
369 '''
370
371 if not interface:
372 interface = self.interfaces[0]
373
374 if self._is_enabled():
375 list_ = list(wifi.Cell.all(interface))
376 for i in range(len(list_)):
377 self.names[list_[i].ssid] = list_[i]
378 else:
379 raise Exception('Wifi not enabled.')
380
381 def _get_network_info(self, name):
382 '''
383 Starts scanning for available Wi-Fi networks and returns the available,
384 devices.
385
386 .. versionadded:: 1.2.5
387 '''
388 ret_list = {}
389 ret_list['ssid'] = self.names[name].ssid
390 ret_list['signal'] = self.names[name].signal
391 ret_list['quality'] = self.names[name].quality
392 ret_list['frequency'] = self.names[name].frequency
393 ret_list['bitrates'] = self.names[name].bitrates
394 ret_list['encrypted'] = self.names[name].encrypted
395 ret_list['channel'] = self.names[name].channel
396 ret_list['address'] = self.names[name].address
397 ret_list['mode'] = self.names[name].mode
398 if not ret_list['encrypted']:
399 return ret_list
400 else:
401 ret_list['encryption_type'] = self.names[name].encryption_type
402 return ret_list
403
404 def _get_available_wifi(self):
405 '''
406 Returns the name of available networks.
407
408 .. versionadded:: 1.2.5
409 .. versionchanged:: 1.4.0
410 return a proper list of elements instead of dict_keys
411 '''
412 return list(self.names.keys())
413
414 def _connect(self, network, parameters, interface=None):
415 '''
416 Expects 2 parameters:
417 - name/ssid of the network.
418 - parameters: dict type
419 - password: string or None
420
421 .. versionadded:: 1.2.5
422 '''
423 if not interface:
424 interface = self.interfaces[0]
425
426 result = None
427 try:
428 self._enable()
429 finally:
430 password = parameters['password']
431 cell = self.names[network]
432 result = wifi.Scheme.for_cell(
433 interface, network, cell, password
434 )
435 return result
436
437 def _disconnect(self, interface=None):
438 '''
439 Disconnect all the networks managed by Network manager.
440
441 .. versionadded:: 1.2.5
442 '''
443 if not interface:
444 interface = self.interfaces[0]
445
446 if self._nmcli_version() >= (1, 2, 6):
447 call(['nmcli', 'dev', 'disconnect', interface])
448 else:
449 call(['nmcli', 'nm', 'enable', 'false'])
450
451 def _enable(self):
452 '''
453 Wifi interface power state is set to "ON".
454
455 .. versionadded:: 1.3.2
456 '''
457 return call(['nmcli', 'radio', 'wifi', 'on'])
458
459 def _disable(self):
460 '''
461 Wifi interface power state is set to "OFF".
462
463 .. versionadded:: 1.3.2
464 '''
465 return call(['nmcli', 'radio', 'wifi', 'off'])
466
467 def _nmcli_version(self):
468 '''
469 .. versionadded:: 1.3.2
470 '''
471 version = Popen(['nmcli', '-v'], stdout=PIPE)
472 version = version.communicate()[0].decode('utf-8')
473 while version and not version[0].isdigit():
474 version = version[1:]
475 return tuple(map(int, (version.split('.'))))
476
477
478 def instance():
479 if whereis_exe('nmcli'):
480 return NMCLIWifi()
481
482 return LinuxWifi()