按组名获取组id(Python,Unix)

2024-04-29 12:38:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Python将组id获取到相应的组名。 该例程必须适用于类Unix操作系统(Linux和Mac OS X)。

这就是我目前发现的

>>> import grp
>>> for g in grp.getgrall():
...     if g[0] == 'wurzel':
...         print g[2]

Tags: inimportidforifoslinuxmac
3条回答

使用perl:

$grp_id = getgrnam($ARGV[0]);
print $grp_id."\n";

^{}

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

数字组ID位于索引2处,或者是倒数第二个,或者属性gr_gid

root的GID为0:

>>> grp.getgrnam('root')
('root', 'x', 0, ['root'])
>>> grp.getgrnam('root')[-2]
0
>>> grp.getgrnam('root').gr_gid
0
>>>

如果您阅读grp module documentation,您将看到grp.getgrnam(groupname)将从组数据库返回一个条目,这是一个类似元组的对象。您可以按索引或按属性访问信息:

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

其他条目包括名称、加密密码(通常为空,如果使用卷影文件,则为伪值)和所有组成员名称。这在任何Unix系统上都可以正常工作,包括我的Mac OS X笔记本电脑:

>>> 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']

该模块还提供了一种通过gid获取条目的方法,正如您所发现的,还提供了一种循环遍历数据库中所有条目的方法:

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

最后但并非最不重要的一点是,python提供了类似的功能,可以在具有类似API的pwdspwd模块中获取有关密码和阴影文件的信息。

相关问题 更多 >