Manual fixes to Python file

To see if I like the rules
This commit is contained in:
Geoffrey Frogeye 2025-05-08 18:29:03 +02:00
parent 34b545890d
commit 8179433c41
10 changed files with 612 additions and 547 deletions

View file

@ -1,14 +1,15 @@
"""
Add the networks saved in wireless_networks to wpa_supplicant,
without restarting it or touching its config file.
Add the networks saved in wireless_networks to wpa_supplicant.
Does not restart it or touch its config file.
"""
import json
import os
import pathlib
import re
import subprocess
NETWORKS_FILE = "/etc/keys/wireless_networks.json"
NETWORKS_FILE = pathlib.Path("/etc/keys/wireless_networks.json")
def wpa_cli(command: list[str]) -> list[bytes]:
@ -20,7 +21,7 @@ def wpa_cli(command: list[str]) -> list[bytes]:
return lines
network_numbers: dict[str, int] = dict()
network_numbers: dict[str, int] = {}
networks_tsv = wpa_cli(["list_networks"])
networks_tsv.pop(0)
for network_line in networks_tsv:
@ -34,8 +35,8 @@ for network_line in networks_tsv:
).decode()
network_numbers[ssid] = number
if os.path.isfile(NETWORKS_FILE):
with open(NETWORKS_FILE) as fd:
if NETWORKS_FILE.is_file():
with NETWORKS_FILE.open() as fd:
networks = json.load(fd)
for network in networks:
@ -54,4 +55,5 @@ if os.path.isfile(NETWORKS_FILE):
value_str = str(value)
ret = wpa_cli(["set_network", number_str, key, value_str])
if ret[0] != b"OK":
raise RuntimeError(f"Couldn't set {key} for {ssid}, got {ret}")
msg = f"Couldn't set {key} for {ssid}, got {ret}"
raise RuntimeError(msg)

39
os/wireless/import.py Executable file → Normal file
View file

@ -1,7 +1,4 @@
"""
Exports Wi-Fi networks configuration stored in pass
into a format readable by Nix.
"""
"""Exports Wi-Fi networks from password store."""
# TODO EAP ca_cert=/etc/ssl/... probably won't work. Example fix:
# builtins.fetchurl {
@ -11,52 +8,60 @@ into a format readable by Nix.
import json
import os
import pathlib
import subprocess
import yaml
# passpy doesn't handle encoding properly, so doing this with calls
PASSWORD_STORE = os.environ["PASSWORD_STORE_DIR"]
PASSWORD_STORE = pathlib.Path(os.environ["PASSWORD_STORE_DIR"])
SUBFOLDER = "wifi"
def list_networks() -> list[str]:
def list_networks() -> list[pathlib.Path]:
paths = []
pass_folder = os.path.join(PASSWORD_STORE, SUBFOLDER)
pass_folder = PASSWORD_STORE / SUBFOLDER
for filename in os.listdir(pass_folder):
if not filename.endswith(".gpg"):
continue
filepath = os.path.join(pass_folder, filename)
if not os.path.isfile(filepath):
filepath = pass_folder / filename
if not filepath.is_file():
continue
file = filename[:-4]
path = os.path.join(SUBFOLDER, file)
path = pathlib.Path(SUBFOLDER, file)
paths.append(path)
paths.sort()
return paths
networks: list[dict[str, str | list[str] | int]] = list()
networks: list[dict[str, str | list[str] | int]] = []
for path in list_networks():
proc = subprocess.run(["pass", path], stdout=subprocess.PIPE, check=True)
proc = subprocess.run(
["pass", path], # noqa: S607
stdout=subprocess.PIPE,
check=True,
)
raw = proc.stdout.decode()
split = raw.split("\n")
password = split[0]
data = yaml.safe_load("\n".join(split[1:])) or dict()
data = yaml.safe_load("\n".join(split[1:])) or {}
# Helpers to prevent repetition
suffixes = data.pop("suffixes", [""])
data.setdefault("key_mgmt", ["WPA-PSK"] if password else ["NONE"])
if password:
if any(map(lambda m: "PSK" in m.split("-"), data["key_mgmt"])):
if any("PSK" in m.split("-") for m in data["key_mgmt"]):
data["psk"] = password
if any(map(lambda m: "EAP" in m.split("-"), data["key_mgmt"])):
if any("EAP" in m.split("-") for m in data["key_mgmt"]):
data["password"] = password
assert "ssid" in data, f"{path}: Missing SSID"
if "ssid" in data:
msg = f"{path}: Missing SSID"
raise KeyError(msg)
data.setdefault("disabled", 0)
for suffix in suffixes:
@ -64,5 +69,5 @@ for path in list_networks():
network["ssid"] += suffix
networks.append(network)
with open("wireless_networks.json", "w") as fd:
with pathlib.Path("wireless_networks.json").open("w") as fd:
json.dump(networks, fd, indent=4)