python库介绍-spwd:shadow密码数据库

简介

pwd可以访问Unix shadow密码数据库。 2.5新增。通常需要为root用户。

密码数据库项由结构体spwd(类似元组)表示,参见shadow.h:

序号 属性 含义
0 sp_nam Login name
1 sp_pwd Encrypted password
2 sp_lstchg Date of last change
3 sp_min Minimal number of days between changes
4 sp_max Maximum number of days between changes
5 sp_warn Number of days before password expires to warn user about it
6 sp_inact Number of days after password expires until account is blocked
7 sp_expire Number of days since 1970-01-01 until account is disabled
8 sp_flag Reserved

sp_nam和sp_pwd为字符串,其他为整型。

spwd方法

  • spwd.getspnam(name)

    Return the shadow password database entry for the given user name.

  • spwd.getspall()

    Return a list of all available shadow password database entries, in arbitrary order.

"""
Name: spwd_demo.py

Tesed in python3.5/2.7/2.6
"""
import os
import spwd

print(spwd.getspnam('root'))

print("------ All Passwords ------")
for item in spwd.getspall():
    print(item)

执行结果:

# python3 spwd_demo.py 
spwd.struct_spwd(sp_namp='root', sp_pwdp='$6$lI1PEE0n$aM1p4k/rycTFYmS44mKPulvtPTxpVmZ7BH.bIuqoOI2ZDJUgQqTgSBEAEPdhLgVhFygwlZkOInP0RMxIk0dQE1', sp_lstchg=16916, sp_min=0, sp_max=99999, sp_warn=7, sp_inact=-1, sp_expire=-1, sp_flag=-1)
------ All Passwords ------
spwd.struct_spwd(sp_namp='root', sp_pwdp='$6$lI1PEE0n$aM1p4k/rycTFYmS44mKPulvtPTxpVmZ7BH.bIuqoOI2ZDJUgQqTgSBEAEPdhLgVhFygwlZkOInP0RMxIk0dQE1', sp_lstchg=16916, sp_min=0, sp_max=99999, sp_warn=7, sp_inact=-1, sp_expire=-1, sp_flag=-1)

...

$ python spwd_demo.py 
Traceback (most recent call last):
  File "spwd_demo.py", line 12, in <module>
    print(spwd.getspnam('root'))
KeyError: 'getspnam(): name not found'

可见用普通用户执行会报异常KeyError。

参考资料

links