โมดูล spwd ให้เข้าถึง UNIX Shadow Password Database (/etc/shadow) ต้องมีสิทธิ์ Root
import spwd
โครงสร้าง Shadow Entry
| Index | Attribute | คำอธิบาย |
|---|---|---|
| 0 | sp_namp | Login Name |
| 1 | sp_pwdp | Encrypted Password |
| 2 | sp_lstchg | วันสุดท้ายที่เปลี่ยน Password (Days since 1970-01-01) |
| 3 | sp_min | Min Days ระหว่างการเปลี่ยน Password |
| 4 | sp_max | Max Days ระหว่างการเปลี่ยน Password |
| 5 | sp_warn | Warn Days ก่อนหมดอายุ |
| 6 | sp_inact | Days หลังหมดอายุจน Lock Account (-1 = ไม่ Lock) |
| 7 | sp_expire | Account Expiry Date (Days since 1970-01-01, -1 = ไม่หมดอายุ) |
| 8 | sp_flag | Reserved |
เมธอดหลัก
getspnam(name)- ค้นหาจาก Usernamegetspall()- คืน Entries ทั้งหมด
โค้ดตัวอย่าง
import spwd
import datetime
def days_to_date(days):
if days == -1:
return "Never"
return datetime.date(1970, 1, 1) + datetime.timedelta(days=days)
# ค้นหา User เฉพาะ
root_entry = spwd.getspnam('root')
print("Root:", root_entry)
# วนลูปทั้งหมด
for entry in spwd.getspall():
print(f"User: {entry.sp_namp:20} "
f"Pass: {entry.sp_pwdp[:20]:20}... "
f"LastChg: {days_to_date(entry.sp_lstchg)} "
f"Max: {entry.sp_max} "
f"Warn: {entry.sp_warn} "
f"Expire: {days_to_date(entry.sp_expire)}")
ผลลัพธ์ (ต้อง sudo)
Root: spwd.struct_spwd(sp_namp='root', sp_pwdp='!', sp_lstchg=17778, sp_min=0, sp_max=99999, sp_warn=7, sp_inact=-1, sp_expire=-1, sp_flag=-1) User: root Pass: ! LastChg: 2018-08-15 Max: 99999 Warn: 7 Expire: Never User: unix_user Pass: $6$47n9s0Ep$znWkg... Max: 99999 Warn: 7 Expire: Never User: mongodb Pass: ! LastChg: 2018-08-15 Max: 99999 Warn: 7 Expire: Never ...
สถานะ Password (จาก sp_pwdp)
| ค่า | ความหมาย |
|---|---|
! หรือ * | Account Locked / No Password / System Account |
$6$... | SHA-512 Hash (Active Password) |
$5$... | SHA-256 Hash |
$y$... | Yescrypt Hash |
การประยุกต์ใช้
- Password Expiry Monitoring
- Account Audit (Locked/Expired Accounts)
- Password Policy Compliance Check
- Integration กับ Authentication System
⚠️ ข้อควรระวัง
- ต้องรันด้วย Root Privileges (sudo)
- ข้อมูล Sensitivity สูง - จัดการระมัดระวัง
- ไม่ควร Log Password Hash
- บางระบบใช้
/etc/shadowแบบ Read-only สำหรับ Non-root