如何在Linux(可能还有其他unix)中列出一个组的所有成员?


当前回答

下面的shell脚本将遍历所有用户,并只打印属于给定组的用户名:

#!/usr/bin/env bash
getent passwd | while IFS=: read name trash
do
    groups $name 2>/dev/null | cut -f2 -d: | grep -i -q -w "$1" && echo $name
done
true

使用的例子:

./script 'DOMAIN+Group Name'

注意:此解决方案将检查NIS和LDAP中的用户和组(不仅仅是passwd和group文件)。它还将考虑未添加到组但已将组设置为主组的用户。

编辑:为用户不属于同名组的罕见场景添加了修复。

编辑:以shell脚本的形式编写;根据@Max Chernyak aka hakunin的建议,添加了true以0状态退出;为了跳过那些偶然的组,丢弃了stderr:找不到组ID xxxxxx的名称。

其他回答

Zed的实现应该扩展到其他一些主要UNIX上。

有人可以使用Solaris或HP-UX硬件吗?没有测试这些案例。

#!/usr/bin/perl
#
# Lists members of all groups, or optionally just the group
# specified on the command line
#
# Date:         12/30/2013
# Author:       William H. McCloskey, Jr.
# Changes:      Added logic to detect host type & tailor subset of getent (OSX)
# Attribution:
#   The logic for this script was directly lifted from Zed Pobre's work.
#     See below for Copyright notice.
#   The idea to use dscl to emulate a subset of the now defunct getent on OSX
#     came from
#       http://zzamboni.org/\
#         brt/2008/01/21/how-to-emulate-unix-getent-with-macosxs-dscl/
#     with an example implementation lifted from
#       https://github.com/petere/getent-osx/blob/master/getent
#
# 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";

# Only run on supported $os:
my $os;
($os)=(`uname -a` =~ /^([\w-]+)/);
unless ($os =~ /(HU-UX|SunOS|Linux|Darwin)/)
    {die "\$getent or equiv. does not exist:  Cannot run on $os\n";}

my $wantedgroup = shift;

my %groupmembers;

my @users;

# Acquire the list of @users based on what is available on this OS:
if ($os =~ /(SunOS|Linux|HP-UX)/) {
    #HP-UX & Solaris assumed to be like Linux; they have not been tested.
    my $usertext = `getent passwd`;
    @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
};
if ($os =~ /Darwin/) {
    @users = `dscl . -ls /Users`;
    chop @users;
}

# Now just do what Zed did - thanks Zed.
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";
    }
}

如果有更好的方法来分享这个建议,请告诉我;我考虑了很多方法,这就是我想到的。

你可以在一个命令行中完成:

cut -d: -f1,4 /etc/passwd | grep $(getent group <groupname> | cut -d: -f3) | cut -d: -f1

上面的命令列出了所有使用groupname作为主组的用户

如果还希望列出具有groupname的用户作为次要组,则使用以下命令

getent group <groupname> | cut -d: -f4 |  tr ',' '\n'

我认为最简单的方法是以下步骤,你不需要安装任何软件包或软件:

首先,你找出你想知道的用户组的GID,有很多方法: cat /etc/group(最后一列是GID) Id用户(用户是属于组的人) 现在,您将在文件/etc/passwd中列出所有用户,但是您将使用以下后续命令应用一些过滤器,以获得前一个组的成员。

cut -d: -f1,4 /etc/passwd |grep GID (GID是你从步骤1中得到的数字)

切命令将选择一些“列”的文件,参数d设置分隔符”:“在这种情况下,参数- f选择“字段”(或列)在案例1和4所示(在/ etc / passwd文件,1º列是用户的名称和4º是用户所属的组的GID),完成| grep GID将滤波器组(4º列),你选择了。

我所做的与上面的perl代码类似,但是用本地perl函数替换了getent和id。它要快得多,应该可以跨不同的*nix口味工作。

#!/usr/bin/env perl

use strict;
my $arg=shift;
my %groupMembers; # defining outside of function so that hash is only built once for multiple function calls

sub expandGroupMembers{
my $groupQuery=shift;
unless (%groupMembers){
    while (my($name,$pass,$uid,$gid,$quota,$comment,$gcos,$dir,$shell,$expire)=getpwent()) {
            my $primaryGroup=getgrgid($gid);
            $groupMembers{$primaryGroup}->{$name}=1;
    }
    while (my($gname,$gpasswd,$gid,$members)=getgrent()) {
            foreach my $member (split / /, $members){
                    $groupMembers{$gname}->{$member}=1;
            }
    }
}
my $membersConcat=join(",",sort keys %{$groupMembers{$groupQuery}});
return "$membersConcat" || "$groupQuery Does have any members";
}
print &expandGroupMembers($arg)."\n";
lid -g groupname | cut -f1 -d'('