PyMOTW: grp

grp – Unix Group Database

Purpose:

Read group data from Unix group database.

Python Version:

1.4 and later

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

Index

Attribute

Meaning

0

gr_name

Name

1

gr_passwd

Password, if any (encrypted)

2

gr_gid

Numerical id (integer)

3

gr_mem

Names of group members

The name and password values are both strings, the GID is an integer, and the members are reported as a list of strings.

Querying All Groups

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

importgrpimportoperator

# Load all of the user data, sorted by usernameall_groups=grp.getgrall()interesting_groups=sorted((gforginall_groupsifnotg.gr_name.startswith('_')),key=operator.attrgetter('gr_name'))

# Find the longest length for the namename_length=max(len(g.gr_name)forgininteresting_groups)+1