您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

如果我绝对必须自己做,则可能相反:使用id获取系统上每个用户的组(这将使NSS看到所有源),并使用Perl或类似的方法来维护哈希发现的每个组的表,注意该用户的成员资格。

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

编辑2:有人提醒我,getent passwd它将返回系统上所有用户的列表,包括来自LDAP / NIS / etc。的用户 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";
    }
}
其他 2022/1/1 18:13:37 有599人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶