Files
passwd2systemd-userdb/main.py
T

65 lines
1.7 KiB
Python
Executable File

#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
def main():
parser = argparse.ArgumentParser(
description="Convert a passwd file to a directory of systemd JSON user records.",
)
parser.add_argument(
"passwd_file",
type=Path,
help="Path to the passwd file.",
)
parser.add_argument(
"output_dir",
type=Path,
help="Path to a directory to store json user records.",
)
args = parser.parse_args()
parsed_users = parse_passwd_file(args.passwd_file)
for user in parsed_users:
print(json.dumps(user, indent=2))
def parse_passwd_file(passwd_file: Path) -> list[dict]:
users = []
with passwd_file.open("r") as f:
for line in f:
if line.startswith("#") or not line.strip():
continue
parts = line.strip().split(":")
if len(parts) < 7:
print(f"Warning: Skipping malformed line: {line.strip()}")
continue
user = {
"name": parts[0],
"uid": int(parts[2]),
"gid": int(parts[3]),
"gecos": parse_gecos(parts[4]),
"home": parts[5],
"shell": parts[6],
}
users.append(user)
return users
def parse_gecos(gecos: str) -> dict:
parts = gecos.split(",")
return {
"full_name": parts[0] if len(parts) > 0 else "",
"room_number": parts[1] if len(parts) > 1 else "",
"work_phone": parts[2] if len(parts) > 2 else "",
"home_phone": parts[3] if len(parts) > 3 else "",
"other": parts[4] if len(parts) > 4 else "",
}
if __name__ == "__main__":
main()