getpwname
只能获得gid
的{{1}}。
username
import pwd
myGroupId = pwd.getpwnam(username).pw_gid
只能获得脚本用户getgroups
。
groups
如何获得一个import os
myGroupIds = os.getgroups()
的{{1}} groups
,就像username
命令一样?
id -Gn
答案 0 :(得分:25)
#!/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
答案 1 :(得分:2)
当用户属于一个或多个组,其中多个组名映射到同一id -Gn
时,gid
的结果可能与发布的答案不同。例如,如果/etc/groups
与此类似:
% ypcat group | grep mygroup
mygroup:*:66485:user1,user2,user3,...
mygroup1:*:66485:user101,user102,user103,...
mygroup2:*:66485:user201,user202,user203,...
...
如果用户未列在mygroup
但在mygroup<n>
中,id -Gn
会返回mygroup
,但发布的答案会返回mygroup<n>
。
似乎在我的环境中,因为UNIX组可以有数百或数千个用户,这是一个常见的组管理策略,虽然我不确切知道每个组的用户限制是什么以及为什么id -Gn
始终返回mygroup
。
尽管如此,通过下面的代码,我得到了id -Gn
的匹配:
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]
答案 2 :(得分:2)
如果您想要当前用户&#39;基团。
import os, grp
[grp.getgrgid(g).gr_name for g in os.getgroups()]
os.getgroups()返回当前用户的gid列表。
grp.getgrgid(g)返回有关组
的详细信息答案 3 :(得分:2)
我发现只有在系统中非本地用户(例如ldap,sssd + ldap,freeIPA)而不在子进程中调用id时才能正常工作的方法是调用getgrouplist
c函数(在通过一些抽象之后最终被id调用:
#!/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 enought?
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(user.pw_name, user.pw_gid, byref(grouplist), byref(ngrouplist))
# if 50 groups was not enought 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 xrange(0, ct):
gid = grouplist[i]
print grp.getgrgid(gid).gr_name