栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何列出Linux组中的所有用户?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何列出Linux组中的所有用户?

不幸的是,据我所知,没有很好的便携式方法可以做到这一点。如果您尝试解析/ etc /
group(如其他人所建议的那样),则会错过以该组为主要组的用户以及通过UNIX平面文件(例如LDAP,NIS, pam-pgsql等)。

如果我绝对必须自己做,则可能相反:使用

id
来获取系统上每个用户的组(这将使NSS看到所有源),并使用Perl或类似的方法来维护哈希发现的每个组的表,注意该用户的成员资格。

编辑:当然,这给您留下了类似的问题:如何获取系统上每个用户的列表。由于我的位置仅使用平面文件和LDAP,因此我只能从这两个位置获取列表,但这可能对您的环境不适用。

编辑2:有人提醒我,

getent passwd
它将返回系统上所有用户的列表,包括来自LDAP / NIS / etc。的用户,
getentgroup
仍然仍然仅通过默认组条目错过作为成员的用户,因此启发了我写这个快速技巧。

#!/usr/bin/perl -T## Lists members of all groups, or optionally just the group# specified on the command line## Copyright © 2010-2013 by Zed Pobre (zed@debian.org or zed@resonant.org)## Permission to use, copy, modify, and/or distribute this software for any# purpose with or without fee is hereby granted, provided that the above# copyright notice and this permission notice appear in all copies.#use strict; use warnings;$ENV{"PATH"} = "/usr/bin:/bin";my $wantedgroup = shift;my %groupmembers;my $usertext = `getent passwd`;my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;foreach my $userid (@users){    my $usergrouptext = `id -Gn $userid`;    my @grouplist = split(' ',$usergrouptext);    foreach my $group (@grouplist)    {        $groupmembers{$group}->{$userid} = 1;    }}if($wantedgroup){    print_group_members($wantedgroup);}else{    foreach my $group (sort keys %groupmembers)    {        print "Group ",$group," has the following members:n";        print_group_members($group);        print "n";    }}sub print_group_members{    my ($group) = @_;    return unless $group;    foreach my $member (sort keys %{$groupmembers{$group}})    {        print $member,"n";    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399088.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号