不幸的是,据我所知,没有很好的便携式方法可以做到这一点。如果您尝试解析/ 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"; }}


