I want to use Python to get the group id to a corresponding group name.
The routine must work for Unix-like OS (Linux and Mac OS X).
This is what I found so far
>>> import grp
>>> for g in grp.getgrall():
... if g[0] == 'wurzel':
... print g[2]
If you read the grp module documentation you’ll see that grp.getgrnam(groupname) will return one entry from the group database, which is a tuple-like object. You can either access the information by index or by attribute:
Other entries are the name, the encrypted password (usually empty, if using a shadow file, it’ll be a dummy value) and all group member names. This works fine on any Unix system, including my Mac OS X laptop:
The module also offers a method to get entries by gid, and as you discovered, a method to loop over all entries in the database:
Last but not least, python offers similar functionality to get information on the password and shadow files, in the pwd and spwd modules, which have a similar API.