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

nwo49xxi  于 2023-03-01  发布在  Linux
关注(0)|答案(5)|浏览(246)

getpwname只能获得usernamegid

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

getgroups只能获取脚本用户的groups

import os
myGroupIds = os.getgroups()

如何获得任意一个username的所有groups,就像id -Gn命令一样?

id -Gn `whoami`
czq61nw1

czq61nw11#

下面的代码假设您只对本地用户感兴趣,但对由目录服务器支持的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
zlwx9yxi

zlwx9yxi2#

如果您想要当前用户的组。

import os, grp
[grp.getgrgid(g).gr_name for g in os.getgroups()]

os.getgroups()返回当前用户的GID列表。
grp.getgrgid(g)返回有关组的详细信息

hk8txs48

hk8txs483#

我发现当用户不在系统本地时(例如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)
ivqmmu1c

ivqmmu1c4#

当用户属于一个或多个组,而其中多个组名称Map到同一个gid时,id -Gn的结果可能与发布的答案不同。例如,如果/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]
3bygqnnd

3bygqnnd5#

自Python 3.3起:

import os
import pwd

uid = os.getuid()
user = pwd.getpwuid(uid)
gl = os.getgrouplist(user.pw_name, user.pw_gid)
print(gl)

相关问题