views:

997

answers:

4

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. Thanks!

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 =)

+10  A: 

the grp module is your friend. Look at grp.getgrall() to get a list of all groups and their members.

EDIT example:

import grp
groups = grp.getgrall()
for group in groups:
    for user in group[3]:
        print user, group[0]
d0k
This worked, but it seems, that its not listing all the users. Any thoughts? $ ./script.py | wc -l 81 $ sudo cat /etc/shadow | wc -l 406
Derek B.
I think what i'm seeing is that the server I'm using this on has a ton of groups with no users in them (old, old groups) that happen to still be around. This script ignores groups with no users in them, which is fine, that's what I need! =)
Derek B.
This solution only lists the users' *secondary* groups. My read of question was that it asks for "their group", ie the [singular] user's *primary* group?
Martin Carpenter
See S.Lott's answer for a solution which shows only the primary group
d0k
+6  A: 

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]
S.Lott
+3  A: 

sh/bash:

getent passwd | cut -f1 -d: | while read name; do echo -n "$name " ; groups $name ; done
Joachim Sauer
Nice but he asked explicitely for Python...
bortzmeyer
He did, but he added "Take a whack at it in any language but I'd prefer python."
Joachim Sauer
A: 

how to show all logged on users?

Predator
Just use the "users" command.
Derek B.