Proper way to query user and group database on a Unix host?

Chris Brannon cmbrannon at
Wed Jul 23 08:55:15 CEST 2008

Mike MacCana <mmaccana at> writes:

> Hi folks,
> What's the proper way to query the passwd and group database on a Unix
> host? 

Use the pwd and grp modules, respectively.

>     ## Get the full group database entry, leave just the user list,
>     ## and split the list on comma
>     groupname=users
>     groupsusers = commands.getoutput('getent group '+groupname).split(':',-1)[3].split(',')

Instead, do this:

import grp
groupname = 'users'
groupusers = grp.getgrnam(groupname)[3]
print 'The group named "users" contains:'
for username in groupusers:
    print username

The functions from the grp and pwd modules return tuples.  The docs describe
their formats.

Hope this helps,
-- Chris

More information about the Python-list mailing list