Implement basic passwd parser

This commit is contained in:
2026-05-26 01:39:38 +09:00
parent fafe487645
commit bbb9dd8fe4
2 changed files with 91 additions and 0 deletions
Executable
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
import argparse
import sys
import json
def main():
parser = argparse.ArgumentParser(
description="Convert a passwd file to a directory of systemd JSON user records.",
)
parser.add_argument(
"passwd_file",
help="Path to the passwd file.",
)
parser.add_argument(
"output_dir",
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):
users = []
with open(passwd_file, "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()}", file=sys.stderr)
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):
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()