Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to list users and groups

Tags:

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

like image 690
Derek Avatar asked Jan 07 '09 19:01

Derek


People also ask

How do I get a list of users in Python?

PROGRAM. First, import the psutil Python Library to access the users() method. Now, use the method psutil. users() method to get the list of users as a named tuple and assign to the variable user_list.

How do you PWD in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .


2 Answers

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] 
like image 78
S.Lott Avatar answered Sep 17 '22 16:09

S.Lott


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] 
like image 44
d0k Avatar answered Sep 20 '22 16:09

d0k