From c2c9e84692be927bb9760be49a68d9bf089069a7 Mon Sep 17 00:00:00 2001 From: Kenneth Raplee Date: Sun, 30 Jul 2023 20:39:10 -0700 Subject: [PATCH] Refactor src/setup-nic.py using pathlib --- src/setup-nic.py | 53 +++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 19 deletions(-) diff --git a/src/setup-nic.py b/src/setup-nic.py index 1a8d5a3..8bb01af 100755 --- a/src/setup-nic.py +++ b/src/setup-nic.py @@ -2,18 +2,35 @@ import os import re +import shutil import sys +from pathlib import Path + + +def file_content(paths): + buffers = [] + for path in paths + with path.open('r') as file: + buffers.append(file.read()) + return "".join(buffers) + args = sys.argv if len(args) != 2: exit(1) nic = args[1] -rcconf = open('/etc/rc.conf', 'r').read() -if os.path.exists('/etc/rc.conf.local'): - rcconflocal = open('/etc/rc.conf.local', 'r').read() -else: - rcconflocal = "None" +etc = Path(os.sep, "etc") +rcconf = etc / "rc.conf" +rcconflocal = etc / "rc.conf.local" +wpa_supplicant = etc / "wpa_supplicant.conf" + +rcconf_paths = [rcconf] + +if rcconflocal.exists(): + rcconf_paths.append(rcconflocal) + +rcconf_content = file_content(rcconf_paths) notnics_regex = "(enc|lo|fwe|fwip|tap|plip|pfsync|pflog|ipfw|tun|sl|faith|" \ "ppp|bridge|wg|wlan)[0-9]+|vm-[a-z]+" @@ -26,21 +43,19 @@ exit(0) if re.search(wifi_driver_regex, nic): - if not os.path.exists('/etc/wpa_supplicant.conf'): - open('/etc/wpa_supplicant.conf', 'a').close() - os.system('chown root:wheel /etc/wpa_supplicant.conf') - os.system('chmod 765 /etc/wpa_supplicant.conf') + if not wpa_supplicant.exists(): + wpa_supplicant.touch() + shutil.chown(wpa_supplicant, user="root", group="wheel") + wpa_supplicant.chmod(0o765) for wlanNum in range(0, 9): - if f'wlan{wlanNum}' not in (rcconf + rcconflocal): + if f'wlan{wlanNum}' not in rcconf_content: break - if f'wlans_{nic}=' not in (rcconf + rcconflocal): - rc = open('/etc/rc.conf', 'a') - rc.writelines(f'wlans_{nic}="wlan{wlanNum}"\n') - rc.writelines(f'ifconfig_wlan{wlanNum}="WPA DHCP"\n') - rc.close() + if f'wlans_{nic}=' not in rcconf_content: + with rcconf.open('a') as rc: + rc.writelines(f'wlans_{nic}="wlan{wlanNum}"\n') + rc.writelines(f'ifconfig_wlan{wlanNum}="WPA DHCP"\n') else: - if f'ifconfig_{nic}=' not in (rcconf + rcconflocal): - rc = open('/etc/rc.conf', 'a') - rc.writelines(f'ifconfig_{nic}="DHCP"\n') - rc.close() + if f'ifconfig_{nic}=' not in rcconf_content: + with rcconf.open('a') as rc: + rc.writelines(f'ifconfig_{nic}="DHCP"\n') os.system(f'/etc/pccard_ether {nic} startchildren')