Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เข้าถึง Shadow Password Database ใน Python (โมดูล spwd)

โมดูล spwd ให้เข้าถึง UNIX Shadow Password Database (/etc/shadow) ต้องมีสิทธิ์ Root

import spwd


โครงสร้าง Shadow Entry

IndexAttributeคำอธิบาย
0sp_nampLogin Name
1sp_pwdpEncrypted Password
2sp_lstchgวันสุดท้ายที่เปลี่ยน Password (Days since 1970-01-01)
3sp_minMin Days ระหว่างการเปลี่ยน Password
4sp_maxMax Days ระหว่างการเปลี่ยน Password
5sp_warnWarn Days ก่อนหมดอายุ
6sp_inactDays หลังหมดอายุจน Lock Account (-1 = ไม่ Lock)
7sp_expireAccount Expiry Date (Days since 1970-01-01, -1 = ไม่หมดอายุ)
8sp_flagReserved

เมธอดหลัก

  • getspnam(name) - ค้นหาจาก Username
  • getspall() - คืน 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