python库介绍-grp:group数据库

简介

grp可以访问Unix组数据库。

组数据库项由结构体group(类似元组)表示,参见pwd.h:

序号 属性 含义
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

gid整型,name和password为字符串,gr_mem为字符串列表。

方法

  • grp.getgrgid(gid)

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

  • grp.getgrnam(name)

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

  • grp.getgrall()

    Return a list of all available group entries, in arbitrary order.

"""
Name: grp_demo.py

Tesed in python3.5
"""
import os
import grp

print(grp.getgrgid(os.getuid()))
print(grp.getgrnam('andrew'))

print("------ All users ------")
for item in grp.getgrall():
    print(item)

执行结果:

$ python grp_demo.py 
grp.struct_group(gr_name='andrew', gr_passwd='x', gr_gid=1000, gr_mem=[])
grp.struct_group(gr_name='andrew', gr_passwd='x', gr_gid=1000, gr_mem=[])
------ All users ------
grp.struct_group(gr_name='root', gr_passwd='x', gr_gid=0, gr_mem=[])
grp.struct_group(gr_name='daemon', gr_passwd='x', gr_gid=1, gr_mem=[])
grp.struct_group(gr_name='bin', gr_passwd='x', gr_gid=2, gr_mem=[])
grp.struct_group(gr_name='sys', gr_passwd='x', gr_gid=3, gr_mem=[])
grp.struct_group(gr_name='adm', gr_passwd='x', gr_gid=4, gr_mem=['syslog', 'andrew'])

...

注意一些用户没有在/etc/group中注明所属组,另外以+或-开头的组名可能也不适用。

参考资料

links