โมดูล pwd ให้เข้าถึง UNIX Password Database (/etc/passwd) คืนค่าเป็น Named Tuple-like Object
import pwd
โครงสร้าง Password Entry
| Index | Attribute | คำอธิบาย |
|---|---|---|
| 0 | pw_name | Login Name / Username |
| 1 | pw_passwd | Encrypted Password (ปัจจุบันมักเป็น 'x' หรือ '*' ใช้ Shadow แทน) |
| 2 | pw_uid | User ID (Numeric) |
| 3 | pw_gid | Primary Group ID |
| 4 | pw_gecos | Real Name / Comment Field |
| 5 | pw_dir | Home Directory |
| 6 | pw_shell | Login Shell |
pw_passwd จะเป็น 'x' หรือ '*' จริงอยู่ใน /etc/shadow (โมดูล spwd)
เมธอดหลัก
getpwuid(uid)- ค้นหาจาก UIDgetpwnam(name)- ค้นหาจาก Usernamegetpwall()- คืน Entries ทั้งหมด
โค้ดตัวอย่าง
import pwd
# ค้นหา User root
root = pwd.getpwnam('root')
print("Root:", root)
# วนลูปทั้งหมด
for entry in pwd.getpwall():
print(f"User: {entry.pw_name:20} UID: {entry.pw_uid:5} "
f"GID: {entry.pw_gid:5} Home: {entry.pw_dir:20} Shell: {entry.pw_shell}")
ผลลัพธ์
Root: pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash') User: root UID: 0 GID: 0 Home: /root Shell: /bin/bash User: daemon UID: 1 GID: 1 Home: /usr/sbin Shell: /usr/sbin/nologin User: bin UID: 2 GID: 2 Home: /bin Shell: /usr/sbin/nologin User: sys UID: 3 GID: 3 Home: /dev Shell: /usr/sbin/nologin User: unix_user UID: 1000 GID: 1000 Home: /home/unix_user Shell: /bin/bash ...
การประยุกต์ใช้
- Resolve UID -> Username (สำหรับ Log, Audit)
- Get Home Directory ของ User
- Check Login Shell
- User Enumeration
- Container/User Namespace Mapping
ตัวอย่าง: หา User จาก UID ของไฟล์
import os, pwd
stat = os.stat('/etc/passwd')
owner = pwd.getpwuid(stat.st_uid)
print(f"Owner of /etc/passwd: {owner.pw_name} (UID: {owner.pw_uid})")
ตัวอย่าง: Filter Regular Users (UID >= 1000)
import pwd
regular_users = [u for u in pwd.getpwall() if u.pw_uid >= 1000 and u.pw_shell != '/usr/sbin/nologin']
for u in regular_users:
print(f"{u.pw_name}: {u.pw_dir} ({u.pw_shell})")