simplify nsswitch finalize script

- remove overbaring debugging
- don't print exceptions or handle exceptions when they are meant to be
fatal
- don't open the file multiple times
- don't check uid, it's inconsequental because we really only need a
writable file
This commit is contained in:
Harald Sitter
2025-03-04 19:39:28 +01:00
parent 8ca406639e
commit a84ed80126

View File

@@ -6,54 +6,21 @@
import os
import sys
def modify_nsswitch():
path = "/etc/nsswitch.conf"
print(f"Checking {path}...") # Debug line
# Read the file
try:
with open(path, "r") as file:
lines = file.readlines()
except Exception as e:
print(f"Error reading {path}: {e}", file=sys.stderr)
raise # Re-raise the exception
modified = False
# Process each line
def replace_lines_in_place(lines):
for i, line in enumerate(lines):
print(f"Checking line: {line.strip()}") # Debug line
if line.startswith("hosts:"):
if "mymachines" in line and "mdns_minimal" not in line:
lines[i] = line.replace("mymachines", "mymachines mdns_minimal [NOTFOUND=return]", 1)
modified = True
print("Added mdns_minimal after mymachines.") # Debug line
elif "mymachines" not in line and "mdns_minimal" not in line:
lines[i] = line.replace("hosts:", "hosts: mdns_minimal [NOTFOUND=return] ", 1)
modified = True
print("Added mdns_minimal.") # Debug line
break
if not line.startswith("hosts: mymachines resolve"):
continue
if not modified:
raise RuntimeError("Expected modification but no changes were made.")
lines[i] = line.replace("mymachines", "mymachines mdns_minimal [NOTFOUND=return]", 1)
return
raise RuntimeError("Expected modification but no changes were made.")
# Write back the modified file
try:
with open(path, "w") as file:
file.writelines(lines)
print("Updated /etc/nsswitch.conf")
except Exception as e:
print(f"Error writing to {path}: {e}", file=sys.stderr)
raise # Re-raise the exception
def modify_nsswitch():
with open("/etc/nsswitch.conf", "r+") as file:
lines = file.readlines()
replace_lines_in_place(lines)
file.seek(0)
file.writelines(lines)
if __name__ == "__main__":
if os.geteuid() != 0:
print("This script must be run as root.", file=sys.stderr)
sys.exit(1)
try:
modify_nsswitch()
except Exception as e:
print(f"Fatal error: {e}", file=sys.stderr)
sys.exit(1)
modify_nsswitch()