如何在Linux(可能还有其他unix)中列出一个组的所有成员?


当前回答

getent group <groupname>;

它可以在Linux和Solaris上移植,并且可以使用本地组/密码文件、NIS和LDAP配置。

其他回答

我已经尝试了grep 'sample-group-name' /etc/group,它将根据这里的示例列出您指定的组的所有成员

lid -g groupname | cut -f1 -d'(' 

再加上grep和tr:

$ grep ^$GROUP /etc/group | grep -o '[^:]*$' | tr ',' '\n'
user1
user2
user3

下面是一个非常简单的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