Python script to list users and groups

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


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

Asked by: Cadie831 | Posted: 24-09-2021

Answer 1

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]

Answered by: Cadie948 | Posted: 25-10-2021

Answer 2

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]

Answered by: Oliver555 | Posted: 25-10-2021

Answer 3


getent passwd | cut -f1 -d: | while read name; do echo -n "$name " ; groups $name ; done

Answered by: Dexter169 | Posted: 25-10-2021

Answer 4

The python call to grp.getgrall() only shows the local groups, unlike the call to getgrouplist c function which retruns all users, e.g. also users in sssd that is backed by an ldap but has enumeration turned off. (like in FreeIPA). After searching for the easiest way to get all groups a users belongs to in python the best way I found was to actually call the getgrouplist c function:


import grp, pwd, os
from ctypes import *
from ctypes.util import find_library

libc = cdll.LoadLibrary(find_library('libc'))

getgrouplist = libc.getgrouplist
# 50 groups should be enought?
ngroups = 50
getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ngroups), POINTER(c_int)]
getgrouplist.restype = c_int32

grouplist = (c_uint * ngroups)()
ngrouplist = c_int(ngroups)

user = pwd.getpwuid(2540485)

ct = getgrouplist(user.pw_name, user.pw_gid, byref(grouplist), byref(ngrouplist))

# if 50 groups was not enough this will be -1, try again
# luckily the last call put the correct number of groups in ngrouplist
if ct < 0:
    getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint *int(ngrouplist.value)), POINTER(c_int)]
    grouplist = (c_uint * int(ngrouplist.value))()
    ct = getgrouplist(user.pw_name, user.pw_gid, byref(grouplist), byref(ngrouplist))

for i in xrange(0, ct):
    gid = grouplist[i]
    print grp.getgrgid(gid).gr_name

Getting a list of all users to run this function on similarly would require to figure out what c call is made by getent passwd and call that in python.

Answered by: Arnold785 | Posted: 25-10-2021

Answer 5

a simple function which is capable to deal with the structure of any one of these files (/etc/passwd and /etc/group).

I believe that this code meets your needs, with Python built-in functions and no additional module:


def read_and_parse(filename):
        Reads and parses lines from /etc/passwd and /etc/group.


          filename : str
            Full path for filename.
    data = []
    with open(filename, "r") as f:
        for line in f.readlines():
        for item in data:
            print("- " + item)


Answered by: William760 | Posted: 25-10-2021

Similar questions

regex - python script using sed groups

i wrote a python script calling sed and have some trouble using the group operator. Here is what I have so far: subprocess.check_call(["sed", "-i","-e","s/\("+str(regex)+"\)/"+str(computeSth(\1))+"/g",headers]) The regex variable simply holds a regular expression. The computeSth function takes as a parameter the first occurrence of the regex

.net - Embed Python script

I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime? Thanks for any help. Rob

Python script knows how much memory it's using

This question already has answers here:

python - What is paste script?

I'm trying to understand what paste script and paster are. The website is far from clear. I used paster to generate pre-made layouts for projects, but I don't get the big picture. As far as I understand, and from the wikipedia entry, it says it's a framework for web frameworks, but that seems reductive. paster create seems to be able to create pre-made layouts for setuptools/distutils enabled packages...

python - check that a script is actually using a proxy from a ip list

I have a list of proxy ip's that I want to use in one of my python scripts, but how do I verify that I am using one of the ip addresses from the list and not my own? I'm using mechanize, but any general explanation of how to do this would be helpful. This is the first time I have worked with proxies, so anything you can tell me will be be really appreciated. Thanks

Getting PHP to run a Python script

I am trying to run a Python program using PHP. Here's the code $command = '/usr/local/bin/python file'; $temp = exec($command, $output); This works through the command line but not while running it through the browser. I am using Apache so probably it needs the right privileges? I am pretty new to Linux and have no idea how to get this working. Any help would be appreciat...

Bash alias to Python script -- is it possible?

The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by taking my ideas and making them Python scripts. Coincident with this idea is another notion I had to ...

zope - Call macro from Python script?

One of our page templates is made up of a bunch of macros. These items are a bunch of html tables. Now, I want a couple of these tables in a Python script to create a PDF. Is there a way call a macro from a Python script and get back the HTML that is produced? If so, can you explain? Thanks Eric

Send an email using python script

Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need. import smtplib SERVER = "localhost" FROM = "" TO = [""] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".jo...

Python - drag file into .exe to run script

I have a Python script that takes the directory path of a text file and converts it into an excel file. Currently I have it running as a console application (compiled with py2exe) and prompts the user for the directory path through raw_input(). How do i make it such that I can drag &amp; drop my text file directly into the .exe of the python script?

Python script to remove lines from file containing words in array

I have the following script which identifies lines in a file which I want to remove, based on an array but does not remove them. What should I change? sourcefile = "C:\\Python25\\PC_New.txt" filename2 = "C:\\Python25\\PC_reduced.txt" offending = ["Exception","Integer","RuntimeException"] def fixup( filename ): print "fixup ", filename fin = open( filename ) fout = open( filename2 ,...

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python