The pwd module in standard library of Python provides access to the password database of user accounts in a Unix/Linux operating system. Entries in this Password database are atored as a tuple-like object. The structure of tuple is according to following passwd structure pwd.h file in CPython API
Index | Attribute | Meaning |
---|---|---|
0 | pw_name | Login name |
1 | pw_passwd | Optional encrypted password |
2 | pw_uid | Numerical user ID |
3 | pw_gid | Numerical group ID |
4 | pw_gecos | User name or comment field |
5 | pw_dir | User home directory |
6 | pw_shell | User command interpreter |
The pwd module defines the following functions −
>>> import pwd >>> dir(pwd) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'getpwall', 'getpwnam', 'getpwuid', 'struct_passwd']
getpwnam() − This function returns record in the password database corresponding to the specified user name
>>> pwd.getpwnam('root') pwd.struct_passwd(pw_name s= 'root', pw_passwd = 'x', pw_uid = 0, pw_gid = 0, pw_gecos = 'root', pw_dir = '/root', pw_shell = '/bin/bash')
getpwuid() − This function returns record in the password database corresponding to given UID
>>> pwd.getpwuid(0) 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')
getpwall() − This function returns a list of tuples. Each tuple contains passwd structure information of each user. The uid and gid items in the structure are integers. If an entry corresponding to the passed parameter cannot be found, KeyError exception is raised.
>>> pwd.getpwnam('hello') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'getpwnam(): name not found: hello'