Python:如何获取一个用户名的组 ID(如 id -Gn )

新手上路,请多包涵

getpwname 只能得到 gidusername

 import pwd
myGroupId = pwd.getpwnam(username).pw_gid

getgroups 只能得到脚本用户的 groups

 import os
myGroupIds = os.getgroups()

我怎样才能得到所有 groups 一个任意 username ,就像 id -Gn 命令一样?

 id -Gn `whoami`

原文由 Ade YU 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 598
2 个回答

以下工作假设您只对本地用户感兴趣,它不适用于目录服务器支持的 sssd 类的东西(例如, ldap )。

 #!/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

原文由 Gareth A. Lloyd 发布,翻译遵循 CC BY-SA 4.0 许可协议

当用户不是系统本地用户(例如 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 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)

原文由 Jens Timmerman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题