net-kingdom/local-identity/src/local_identity/gecos.py

35 lines
921 B
Python
Raw Normal View History

"""
Parse the operator's Linux identity from /etc/passwd and the environment.
GECOS format: "Full Name,Room Number,Work Phone,Home Phone,Other"
We only need the first field (full name).
"""
import os
import pwd
def current_username() -> str:
"""Return the current Linux username."""
return (
os.environ.get("USER")
or os.environ.get("LOGNAME")
or pwd.getpwuid(os.getuid()).pw_name
)
def get_gecos_fullname(username: str) -> str:
"""
Extract the full name from /etc/passwd GECOS for the given username.
Falls back to the username itself if GECOS is absent or unparseable.
"""
try:
entry = pwd.getpwnam(username)
# GECOS may be "Full Name,room,work,home,other" — take the first field
fullname = entry.pw_gecos.split(",")[0].strip()
if fullname:
return fullname
except KeyError:
pass
return username