如何列出 Linux 组中的所有用户?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2835368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to list all users in a Linux group?
提问by user323094
How do I list all members of a group in Linux (and possibly other unices)?
如何在 Linux(可能还有其他 unices)中列出一个组的所有成员?
采纳答案by Zed
Unfortunately, there is no good, portable way to do this that I know of. If you attempt to parse /etc/group, as others are suggesting, you will miss users who have that group as their primary group and anyone who has been added to that group via a mechanism other than UNIX flat files (i.e. LDAP, NIS, pam-pgsql, etc.).
不幸的是,我所知道的没有好的、可移植的方法来做到这一点。如果您尝试解析 /etc/group,正如其他人所建议的那样,您将错过将该组作为其主要组的用户以及通过 UNIX 平面文件以外的机制(即 LDAP、NIS、 pam-pgsql 等)。
If I absolutely had to do this myself, I'd probably do it in reverse: use id
to get the groups of every user on the system (which will pull all sources visible to NSS), and use Perl or something similar to maintain a hash table for each group discovered noting the membership of that user.
如果我绝对必须自己做这件事,我可能会反过来做:用于id
获取系统上每个用户的组(这将拉取 NSS 可见的所有源),并使用 Perl 或类似的东西来维护哈希发现的每个组的表,记录了该用户的成员资格。
Edit: Of course, this leaves you with a similar problem: how to get a list of every user on the system. Since my location uses only flat files and LDAP, I can just get a list from both locations, but that may or may not be true for your environment.
编辑:当然,这会给您带来类似的问题:如何获取系统上每个用户的列表。由于我的位置仅使用平面文件和 LDAP,因此我只能从这两个位置获取列表,但这可能适用于您的环境,也可能不适用于您的环境。
Edit 2: Someone in passing reminded me that getent passwd
will return a list of all users on the system including ones from LDAP/NIS/etc., butgetent group
still will still miss users that are members only via the default group entry, so that inspired me to write this quick hack.
编辑 2:有人路过提醒我,getent passwd
将返回系统上所有用户的列表,包括来自 LDAP/NIS/等的用户,但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 ([email protected] or [email protected])
#
# 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";
}
}
回答by osti
just a little grep and tr:
只是一点点 grep 和 tr:
$ grep ^$GROUP /etc/group | grep -o '[^:]*$' | tr ',' '\n'
user1
user2
user3
回答by Didier Trosset
The following command will list all users belonging to <your_group_name>
, but only those managed by /etc/group
database, not LDAP, NIS, etc. It also works for secondary groups only, it won't list users who have that group set as primary since the primary group is stored as GID
(numeric group ID) in the file /etc/passwd
.
以下命令将列出属于 的所有用户<your_group_name>
,但仅列出由/etc/group
数据库管理的用户,而不是 LDAP、NIS 等。它也仅适用于次要组,它不会列出将该组设置为主要的用户,因为主要组是GID
在文件中存储为(数字组 ID)/etc/passwd
。
awk -F: '/^groupname/ {print ;}' /etc/group
回答by Memo
lid -g groupname | cut -f1 -d'('
回答by Josh H
getent group <groupname>;
It is portable across both Linux and Solaris, and it works with local group/password files, NIS, and LDAP configurations.
它可以跨 Linux 和 Solaris 移植,并且可以与本地组/密码文件、NIS 和 LDAP 配置一起使用。
回答by Pawe? Nadolski
The following shell script will iterate through all users and print only those user names which belong to a given group:
以下 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 "" && echo $name
done
true
Usage example:
用法示例:
./script 'DOMAIN+Group Name'
Note:This solution will check NIS and LDAP for users and groups (not only passwd
and group
files). It will also take into account users not added to a group but having group set as primary group.
注:该解决方案将检查NIS和LDAP用户和组(不仅passwd
和group
文件)。它还将考虑未添加到组但将组设置为主要组的用户。
Edit:Added fix for rare scenario where user does not belong to group with the same name.
编辑:为用户不属于同名组的罕见情况添加了修复。
Edit:written in the form of a shell script; added true
to exit with 0
status as suggested by @Max Chernyak aka hakunin; discarded stderr
in order to skip those occasional groups: cannot find name for group ID xxxxxx
.
编辑:以shell脚本的形式编写;按照@Max Chernyak aka hakunin 的建议添加true
到退出0
状态;丢弃是为了跳过那些偶然的。stderr
groups: cannot find name for group ID xxxxxx
回答by Narayanaperumal Gurusamy
Use Python to list groupmembers:
使用 Python 列出组成员:
python -c "import grp; print grp.getgrnam('GROUP_NAME')[3]"
python -c "import grp; 打印 grp.getgrnam('GROUP_NAME')[3]"
回答by Jose Bagatelli
The following command will list all users belonging to <your_group_name>
, but only those managed by /etc/group
database, not LDAP, NIS, etc. It also works for secondary groups only, it won't list users who have that group set as primary since the primary group is stored as GID
(numeric group ID) in the file /etc/passwd
.
以下命令将列出属于 的所有用户<your_group_name>
,但仅列出由/etc/group
数据库管理的用户,而不是 LDAP、NIS 等。它也仅适用于次要组,它不会列出将该组设置为主要的用户,因为主要组是GID
在文件中存储为(数字组 ID)/etc/passwd
。
grep <your_group_name> /etc/group
回答by andrew lorien
Here is a script which returns a list of users from /etc/passwd and /etc/group it doesn't check NIS or LDAP, but it does show users who have the group as their default group Tested on Debian 4.7 and solaris 9
这是一个脚本,它从 /etc/passwd 和 /etc/group 返回用户列表,它不检查 NIS 或 LDAP,但它确实显示了将该组作为默认组的用户在 Debian 4.7 和 solaris 9 上测试
#!/bin/bash
MYGROUP="user"
# get the group ID
MYGID=`grep $MYGROUP /etc/group | cut -d ":" -f3`
if [[ $MYGID != "" ]]
then
# get a newline-separated list of users from /etc/group
MYUSERS=`grep $MYGROUP /etc/group | cut -d ":" -f4| tr "," "\n"`
# add a newline
MYUSERS=$MYUSERS$'\n'
# add the users whose default group is MYGROUP from /etc/passwod
MYUSERS=$MYUSERS`cat /etc/passwd |grep $MYGID | cut -d ":" -f1`
#print the result as a newline-separated list with no duplicates (ready to pass into a bash FOR loop)
printf '%s\n' $MYUSERS | sort | uniq
fi
or as a one-liner you can cut and paste straight from here (change the group name in the first variable)
或者作为单行,您可以直接从这里剪切和粘贴(更改第一个变量中的组名)
MYGROUP="user";MYGID=`grep $MYGROUP /etc/group | cut -d ":" -f3`;printf '%s\n' `grep $MYGROUP /etc/group | cut -d ":" -f4| tr "," "\n"`$'\n'`cat /etc/passwd |grep $MYGID | cut -d ":" -f1` | sort | uniq
回答by Billy McCloskey
Zed's implementation should probably be expanded to work on some of the other major UNIX.
Zed 的实现可能应该扩展到其他一些主要的 UNIX 上。
Someone have access to Solaris or HP-UX hardware?; did not test those cases.
有人可以访问 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 ([email protected] or [email protected])
#
# 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";
}
}
If there is a better way to share this suggestion, please let me know; I considered many ways, and this is what I came up with.
如果有更好的方式来分享这个建议,请告诉我;我考虑了很多方法,这就是我想出的。