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


当前回答

你可以在一个命令行中完成:

cut -d: -f1,4 /etc/passwd | grep $(getent group <groupname> | cut -d: -f3) | cut -d: -f1

上面的命令列出了所有使用groupname作为主组的用户

如果还希望列出具有groupname的用户作为次要组,则使用以下命令

getent group <groupname> | cut -d: -f4 |  tr ',' '\n'

其他回答

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

下面是一个脚本,返回/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
getent group insert_group_name_here | awk -F ':' '{print $4}' | sed 's|,| |g'

这将返回一个空格分隔的用户列表,我曾在脚本中使用该列表填充数组。

for i in $(getent group ftp | awk -F ':' '{print $4}' | sed 's|,| |g')
    do
        userarray+=("$i")
    done

or

userarray+=("$(getent group GROUPNAME | awk -F ':' '{print $4}' | sed 's|,| |g')")

你可以在一个命令行中完成:

cut -d: -f1,4 /etc/passwd | grep $(getent group <groupname> | cut -d: -f3) | cut -d: -f1

上面的命令列出了所有使用groupname作为主组的用户

如果还希望列出具有groupname的用户作为次要组,则使用以下命令

getent group <groupname> | cut -d: -f4 |  tr ',' '\n'

有一个方便的Debian和Ubuntu包叫做“members”,它提供了这个功能:

描述:显示一个组的成员;默认为所有成员 Members是groups的补充:groups表示指定用户所属的组,Members表示用户 属于特定群体的 ... 你可以请求主要成员,次要成员,都在 一行,每一行都在单独的行上。