librefi/librefi/connectors/networkmanager.py

70 lines
2.1 KiB
Python
Raw Normal View History

2020-11-29 01:14:58 +01:00
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
2020-08-30 16:26:29 +02:00
import subprocess
import re
class NetworkManagerConnector:
NMCLI_BASE = ["nmcli", "--mode", "tabular", "--terse", "--colors", "no"]
def _call_nmcli(self, args, parse=True):
try:
subp = subprocess.check_output(self.NMCLI_BASE + args).decode("utf-8")
except subprocess.CalledProcessError as err:
subp = err.output.decode("utf-8")
2020-08-30 16:26:29 +02:00
if parse:
2020-09-05 01:55:38 +02:00
# if no output
2020-11-29 01:14:58 +01:00
if subp.strip() == "":
2020-09-05 01:55:38 +02:00
return []
2020-08-30 16:26:29 +02:00
return [
[field.replace("\\:", ":")
2020-09-05 01:55:38 +02:00
for field in re.split(r"(?<!\\):", line)]
2020-11-29 01:14:58 +01:00
for line in subp.strip().split("\n")]
2020-08-30 16:26:29 +02:00
2020-11-29 01:14:58 +01:00
return subp
2020-08-30 16:26:29 +02:00
def status(self):
infs = self._call_nmcli(["--fields", "TYPE,NAME",
"connection", "show",
"--active"])
for inf in infs:
if inf[0] == "802-3-ethernet":
return {
"connected": True,
"connection_type": "wired",
"connection_name": inf[1],
}
for inf in infs:
if inf[0] == "802-11-wireless":
return {
"connected": True,
"connection_type": "wifi",
"connection_name": inf[1],
}
return {
"connected": False,
}
def list(self):
infs = self._call_nmcli(["--fields", "SSID,SIGNAL,SECURITY,IN-USE",
"device", "wifi", "list"])
networks = []
for inf in infs:
networks.append({
"ssid": inf[0],
"signal": int(inf[1]),
"is_open": inf[2] == "", # does it require password?
"currently_connected": inf[3] == "*",
})
return networks
def rescan(self):
self._call_nmcli(["device", "wifi", "rescan"], parse=False)
def connect(self, network):
self._call_nmcli(["device", "wifi", "connect",
network["ssid"]], parse=False)