getgrouplist() ?

James T. Dennis jadestar at idiom.com
Sun Jun 16 14:59:43 EDT 2002


Mark McEahern <marklists at mceahern.com> wrote:

>> I need a way to get a back a list of supplemental group ids for a
>> specified uid.  Something like getgrouplist() in my C standard lib.  I
>> don't see a convenient method for this, have I missed it?
>> 
>> The os module contains getgroups(), but that doesn't allow me to
>> specify a uid; it uses only the uid of the current process.

> For what it's worth, the grp module is getting some improvements for 2.3:

>   http://www.python.org/dev/doc/devel/whatsnew/node8.html


 Here's a simple function to build a dictionary of lists, keyed by
 username and containing groupnames for primary GID and any 
 supplemental group memberships:

#!/usr/bin/env python2.2
import grp,pwd

def usersgroups():
	results = {} 				# dict of results
	groups = grp.getgrall()		# list of group entries 
	for i in pwd.getpwall():	# for each user account 
		user = i[0]; gid = i[3]
		# start each user's group list with his/her primary group:
		results[user] =  [grp.getgrgid(gid)[0]]
		# scan groups for this user: 
		for g in groups:
			if user in g[3]: results[user].append(g[0])
	return results 

if __name__=='__main__':

	for i,j in usersgroups().items():
		print i, ":",
		for x in j: 
			print x,
		print 

 It's deliberately simplistic.  I probably could have done something
 fancy with list comprehensions or maps or something, but this 
 should be easy to read.





More information about the Python-list mailing list