pwd – Unix Password Database

Purpose:Read user data from Unix password database.
Available In:1.4 and later

The pwd module can be used to read user information from the Unix password database (usually /etc/passwd). The read-only interface returns tuple-like objects with named attributes for the standard fields of a password record.

Index Attribute Meaning
0 pw_name The user’s login name
1 pw_passwd Encrypted password (optional)
2 pw_uid User id (integer)
3 pw_gid Group id (integer)
4 pw_gecos Comment/full name
5 pw_dir Home directory
6 pw_shell Application started on login, usually a command interpreter

Querying All Users

Suppose you need to print a report of all of the “real” users on a system, including their home directories (for our purposes, “real” is defined as having a name not starting with “_”). To load the entire password database, you would use getpwall(). The return value is a list with an undefined order, so you will need to sort it before printing the report.

import pwd
import operator

# Load all of the user data, sorted by username
all_user_data = pwd.getpwall()
interesting_users = sorted((u 
                            for u in all_user_data 
                            if not u.pw_name.startswith('_')),
                            key=operator.attrgetter('pw_name'))

# Find the longest lengths for a few fields
username_length = max(len(u.pw_name) for u in interesting_users) + 1
home_length = max(len(u.pw_dir) for u in interesting_users) + 1

# Print report headers
fmt = '%-*s %4s %-*s %s'
print fmt % (username_length, 'User', 
             'UID', 
             home_length, 'Home Dir', 
             'Description')
print '-' * username_length, '----', '-' * home_length, '-' * 30

# Print the data
for u in interesting_users:
    print fmt % (username_length, u.pw_name, 
                 u.pw_uid, 
                 home_length, u.pw_dir, 
                 u.pw_gecos)

Most of the example code above deals with formatting the results nicely. The for loop at the end shows how to access fields from the records by name.

$ python pwd_getpwall.py

User        UID Home Dir                 Description
---------- ---- ------------------------ ------------------------------
daemon        1 /var/root                System Services
daemon        1 /var/root                System Services
dhellmann   527 /Users/dhellmann         Doug Hellmann
nobody     4294967294 /var/empty               Unprivileged User
nobody     4294967294 /var/empty               Unprivileged User
postgres    528 /Library/PostgreSQL/9.0  PostgreSQL
root          0 /var/root                System Administrator
root          0 /var/root                System Administrator

Querying User By Name

If you need information about one user, it is not necessary to read the entire password database. Using getpwnam(), you can retrieve the information about a user by name.

import pwd
import sys

username = sys.argv[1]
user_info = pwd.getpwnam(username)

print 'Username:', user_info.pw_name
print 'Password:', user_info.pw_passwd
print 'Comment :', user_info.pw_gecos
print 'UID/GID :', user_info.pw_uid, '/', user_info.pw_gid
print 'Home    :', user_info.pw_dir
print 'Shell   :', user_info.pw_shell

The passwords on my system are stored outside of the main user database in a shadow file, so the password field, when set, is reported as all *.

$ python pwd_getpwnam.py dhellmann

Username: dhellmann
Password: ********
Comment : Doug Hellmann
UID/GID : 527 / 501
Home    : /Users/dhellmann
Shell   : /bin/bash

$ python pwd_getpwnam.py nobody

Username: nobody
Password: *
Comment : Unprivileged User
UID/GID : 4294967294 / 4294967294
Home    : /var/empty
Shell   : /usr/bin/false

Querying User By UID

It is also possible to look up a user by their numerical user id. This is useful to find the owner of a file:

import pwd
import os
import sys

filename = 'pwd_getpwuid_fileowner.py'
stat_info = os.stat(filename)
owner = pwd.getpwuid(stat_info.st_uid).pw_name

print '%s is owned by %s (%s)' % (filename, owner, stat_info.st_uid)
$ python pwd_getpwuid_fileowner.py

pwd_getpwuid_fileowner.py is owned by dhellmann (527)

The numeric user id is can also be used to find information about the user currently running a process:

import pwd
import os

uid = os.getuid()
user_info = pwd.getpwuid(uid)
print 'Currently running with UID=%s username=%s' % (uid, user_info.pw_name)
$ python pwd_getpwuid_process.py

Currently running with UID=527 username=dhellmann

See also

pwd
The standard library documentation for this module.
spwd
Secure password database access for systems using shadow passwords.
grp
The grp module reads Unix group information.
Bookmark and Share