如何在Linux(可能还有其他unix)中列出一个组的所有成员?
当前回答
getent group <groupname>;
它可以在Linux和Solaris上移植,并且可以使用本地组/密码文件、NIS和LDAP配置。
其他回答
下面的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 "$1" && echo $name
done
true
使用的例子:
./script 'DOMAIN+Group Name'
注意:此解决方案将检查NIS和LDAP中的用户和组(不仅仅是passwd和group文件)。它还将考虑未添加到组但已将组设置为主组的用户。
编辑:为用户不属于同名组的罕见场景添加了修复。
编辑:以shell脚本的形式编写;根据@Max Chernyak aka hakunin的建议,添加了true以0状态退出;为了跳过那些偶然的组,丢弃了stderr:找不到组ID xxxxxx的名称。
getent group groupname | awk -F: '{print $4}' | tr , '\n'
这有三个部分:
1 - getent group groupname显示“/etc/group”文件中组的行。替代cat /etc/group | grep groupname。
2 - awk只打印用','分隔的单行中的成员。
3 - tr将','替换为新行,并在一行中打印每个用户。
4 -可选:如果用户太多,你也可以使用另一个管道排序。
问候
lid -g groupname | cut -f1 -d'('
下面是一个非常简单的awk脚本,它考虑了其他答案中列出的所有常见陷阱:
getent passwd | awk -F: -v group_name="wheel" '
BEGIN {
"getent group " group_name | getline groupline;
if (!groupline) exit 1;
split(groupline, groupdef, ":");
guid = groupdef[3];
split(groupdef[4], users, ",");
for (k in users) print users[k]
}
$4 == guid {print $1}'
我将它用于支持ldap的设置,运行在任何具有符合标准的getent和awk的设备上,包括solaris 8+和hpux。
下面是一个脚本,返回/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
或者作为一行程序,您可以直接从这里剪切和粘贴(在第一个变量中更改组名)
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