Python script to list users and groups

Derek picture Derek · Jan 7, 2009 · Viewed 30.3k times · Source

I'm attempting to code a script that outputs each user and their group on their own line like so:

user1 group1  
user2 group1  
user3 group2  
...  
user10 group6

etc.

I'm writing up a script in python for this but was wondering how SO might do this.

p.s. Take a whack at it in any language but I'd prefer python.

EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)

Answer

S.Lott picture S.Lott · Jan 7, 2009

For *nix, you have the pwd and grp modules. You iterate through pwd.getpwall() to get all users. You look up their group names with grp.getgrgid(gid).

import pwd, grp
for p in pwd.getpwall():
    print p[0], grp.getgrgid(p[3])[0]