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


当前回答

使用Python列出组成员:

import grp;打印grp.getgrnam (GROUP_NAME)[3]”

参见https://docs.python.org/2/library/grp.html

其他回答

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

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,它将根据这里的示例列出您指定的组的所有成员

getent group <groupname>;

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

下面是一个脚本,返回/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

下面是另一个Python一行程序,它考虑了用户的默认组成员(来自/etc/passwd)以及组数据库(/etc/group)

python -c "import grp,pwd; print set(grp.getgrnam('mysupercoolgroup')[3]).union([u[0] for u in pwd.getpwall() if u.pw_gid == grp.getgrnam('mysupercoolgroup')[2]])"