不幸的是,据我所知,没有一种好的、便携的方法可以做到这一点.如果像其他人建议的那样try 解析/etc/group,您将错过将该组作为主要组的用户,以及通过UNIX平面文件以外的机制(即LDAP、NIS、pam pgsql等)添加到该组的任何人.
如果我一定要自己做这件事,我可能会反过来做:使用id
来获取系统上每个用户的组(这将获取NSS可见的所有源代码),并使用Perl或类似的工具为发现的每个组维护一个哈希表,并注明该用户的成员身份.
编辑:当然,这会给你带来一个类似的问题:如何获得系统中每个用户的列表.因为我的位置只使用平面文件和LDAP,所以我只能从这两个位置获得一个列表,但对于您的环境来说,这可能是真的,也可能不是真的.
编辑2:有人顺便提醒我,getent passwd
将返回系统上所有用户的列表,包括来自LDAP/NIS/等的用户,but getent group
仍将错过仅通过默认组条目作为成员的用户,因此启发我写这篇快速黑客文章.
#!/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";
}
}