dotfiles/.config/eww/scripts/network.py##hostname.normandy

65 lines
2.1 KiB
Python
Executable File

#!/usr/bin/env python3
import subprocess
import json
import sys
from time import sleep
TRUSTED_NETWORKS = ['honnouji', 'honnouji_2.4']
def wifi():
ssid_cmd = subprocess.run(['iwgetid', '-r'], capture_output = True)
if ssid_cmd.returncode != 0:
return {"connected": False, "ssid": None}
return {"connected": True, "ssid": ssid_cmd.stdout.decode('utf-8').strip()}
def netdev(device: str):
ip_cmd = subprocess.run(['ip', '-j', 'addr', 'show', device], capture_output = True)
if ip_cmd.returncode != 0:
sys.stderr.write(ip_cmd.stdout.decode('utf-8'))
return {"exists": False, "online": False}
ip_data = json.loads(ip_cmd.stdout.decode('utf-8'))[0]
ip4_addr = ""
ip4_prefix_length = 24
addr4_info = list(filter(lambda addr: addr.get("family") == "inet", ip_data["addr_info"]))
if len(addr4_info) >= 1:
ip4_addr = addr4_info[0]["local"]
ip4_prefix_length = addr4_info[0]["prefixlen"]
online = ip_data["operstate"] == "UP" or ip4_addr != ""
connecting = ip_data["operstate"] != "DOWN" and (ip4_addr == "" or not online)
return {
"exists": True,
"online": online,
"connecting": connecting,
"offline": not online and not connecting,
"ip4_addr": ip4_addr,
"ip4_prefix": ip4_prefix_length
}
def trusted(ssid: str | None):
# Don't throw up an "INSECURE" alert when offline
if not ssid:
return True
return ssid in TRUSTED_NETWORKS
while True:
insight = netdev('insight')
wlan0 = netdev('wlan0')
wifi_data = wifi()
connected = insight['exists'] and insight['online'] or wifi_data['connected']
networks = {
"insight": insight,
"wlan0": netdev("wlan0"),
"ezrinet": netdev("ezrinet"),
"wg-mullvad": netdev("wg-mullvad"),
}
result = {
'connected': connected,
"network": networks,
'wifi': wifi_data,
"trusted": True,
"ip4_addrs": [ network.get('ip4_addr') for network in networks.values() if network.get('ip4_addr', "") != "" ]
}
print(json.dumps(result), flush=True)
sleep(1)