Accessing The Unix/Linux password database (pwd)

PythonProgrammingServer Side Programming

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

IndexAttributeMeaning
0pw_nameLogin name
1pw_passwdOptional encrypted password
2pw_uidNumerical user ID
3pw_gidNumerical group ID
4pw_gecosUser name or comment field
5pw_dirUser home directory
6pw_shellUser 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'
raja
Published on 27-Dec-2018 17:46:00
Advertisements