Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get group id by group name (Python, Unix)

Tags:

python

linux

unix

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]
like image 503
SimonSalman Avatar asked Jul 21 '09 08:07

SimonSalman


2 Answers

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:

>>> import grp
>>> groupinfo = grp.getgrnam('root')
>>> print groupinfo[2]
0
>>> print groupinfo.gr_gid
0

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:

>>> import grp
>>> admin = grp.getgrnam('admin')
>>> admin
('admin', '*', 80, ['root', 'admin', 'mj'])
>>> admin.gr_name
'admin'
>>> admin.gr_gid
80
>>> admin.gr_mem
['root', 'admin', 'mj']

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:

>>> grp.getgrgid(80)
('admin', '*', 80, ['root', 'admin', 'mj'])
>>> len(grp.getgrall())
73

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.

like image 176
Martijn Pieters Avatar answered Oct 12 '22 00:10

Martijn Pieters


See grp.getgrnam(name):

grp.getgrnam(name)

Return the group database entry for the given group name. KeyError is raised if the entry asked for cannot be found.

Group database entries are reported as a tuple-like object, whose attributes correspond to the members of the group structure:

Index   Attribute   Meaning

0   gr_name     the name of the group
1   gr_passwd   the (encrypted) group password; often empty
2   gr_gid  the numerical group ID
3   gr_mem  all the group member’s user names

The numerical group ID is at index 2, or 2nd from last, or the attribute gr_gid.

GID of root is 0:

>>> grp.getgrnam('root')
('root', 'x', 0, ['root'])
>>> grp.getgrnam('root')[-2]
0
>>> grp.getgrnam('root').gr_gid
0
>>>
like image 30
gimel Avatar answered Oct 12 '22 00:10

gimel