#!/usr/bin/env python
import grp, pwd
user = "myname"
groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
gid = pwd.getpwnam(user).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
print groups
#!/usr/bin/python
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 enough, if not, we'll repeat the request with the correct nr bellow
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(bytes(user.pw_name, 'UTF-8'), 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 range(0, ct):
gid = grouplist[i]
print(grp.getgrgid(gid).gr_name)
import pwd, grp
def getgroups(user):
gids = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]
gid = pwd.getpwnam(user).pw_gid
gids.append(grp.getgrgid(gid).gr_gid)
return [grp.getgrgid(gid).gr_name for gid in gids]
5条答案
按热度按时间czq61nw11#
下面的代码假设您只对本地用户感兴趣,但对由目录服务器支持的
sssd
(例如ldap
)不起作用。zlwx9yxi2#
如果您想要当前用户的组。
os.getgroups()
返回当前用户的GID列表。grp.getgrgid(g)
返回有关组的详细信息hk8txs483#
我发现当用户不在系统本地时(例如ldap、sssd+ldap、freeIPA),在子进程中不调用id的唯一方法是调用
getgrouplist
c函数(经过一些抽象之后,最终由id调用):ivqmmu1c4#
当用户属于一个或多个组,而其中多个组名称Map到同一个
gid
时,id -Gn
的结果可能与发布的答案不同。例如,如果/etc/groups
类似于:如果用户没有列在
mygroup
中,而是列在mygroup<n>
中,则id -Gn
返回mygroup
,但发布的答案返回mygroup<n>
。在我的环境中,因为UNIX组可以有成百上千的用户,所以这似乎是一种常见的组管理策略,尽管我不知道每个组的用户限制是多少,以及为什么
id -Gn
总是返回mygroup
。尽管如此,通过下面的代码,我得到了与
id -Gn
的匹配:3bygqnnd5#
自Python 3.3起: