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


当前回答

getent group <groupname>;

它可以在Linux和Solaris上移植,并且可以使用本地组/密码文件、NIS和LDAP配置。

其他回答

使用Python列出组成员:

import grp;打印grp.getgrnam (GROUP_NAME)[3]”

参见https://docs.python.org/2/library/grp.html

下面的命令将列出属于<your_group_name>的所有用户,但只列出由/etc/group数据库管理的用户,不包括LDAP、NIS等。它也只适用于次要组,它不会列出将该组设置为主要组的用户,因为主要组存储为/etc/passwd.文件中的GID(数字组ID)

awk -F: '/^groupname/ {print $4;}' /etc/group

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";
    }
}

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

我已经尝试了grep 'sample-group-name' /etc/group,它将根据这里的示例列出您指定的组的所有成员

lid -g groupname | cut -f1 -d'('