python库介绍-pwd:密码数据库

简介

pwd可以访问Unix用户帐户和密码数据库。

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

属性 含义
pw_name Login name
pw_passwd Optional encrypted password
pw_uid Numerical user ID
pw_gid Numerical group ID
pw_gecos User name or comment field
pw_dir User home directory
pw_shell User command interpreter

除了pw_uid和pw_gid是整数外,其他都是字符串。

pwd方法

  • pwd.getpwuid(uid): Return the password database entry for the given numeric user ID.
  • pwd.getpwnam(name) Return the password database entry for the given user name.
  • pwd.getpwall() Return a list of all available password database entries, in arbitrary order.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author Rongzhong Xu 2016-08-22 wechat: pythontesting
"""
Name: pwd_demo.py

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

print(pwd.getpwuid(os.getuid()))
print(pwd.getpwnam('root'))

print("------ All users ------")
for item in pwd.getpwall():
    print(item)

执行结果:

$ python pwd_demo.py
pwd.struct_passwd(pw_name='andrew', pw_passwd='x', pw_uid=1000, pw_gid=1000, pw_gecos='andrew,,,', pw_dir='/home/andrew', pw_shell='/bin/bash')
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')
------ All users ------
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')

...

这种方式通常已经看不到密码,因为密码大多存在/etc/shadows,建议使用spwd。

参考资料

links