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


当前回答

我认为最简单的方法是以下步骤,你不需要安装任何软件包或软件:

首先,你找出你想知道的用户组的GID,有很多方法: cat /etc/group(最后一列是GID) Id用户(用户是属于组的人) 现在,您将在文件/etc/passwd中列出所有用户,但是您将使用以下后续命令应用一些过滤器,以获得前一个组的成员。

cut -d: -f1,4 /etc/passwd |grep GID (GID是你从步骤1中得到的数字)

切命令将选择一些“列”的文件,参数d设置分隔符”:“在这种情况下,参数- f选择“字段”(或列)在案例1和4所示(在/ etc / passwd文件,1º列是用户的名称和4º是用户所属的组的GID),完成| grep GID将滤波器组(4º列),你选择了。

其他回答

再加上grep和tr:

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

我所做的与上面的perl代码类似,但是用本地perl函数替换了getent和id。它要快得多,应该可以跨不同的*nix口味工作。

#!/usr/bin/env perl

use strict;
my $arg=shift;
my %groupMembers; # defining outside of function so that hash is only built once for multiple function calls

sub expandGroupMembers{
my $groupQuery=shift;
unless (%groupMembers){
    while (my($name,$pass,$uid,$gid,$quota,$comment,$gcos,$dir,$shell,$expire)=getpwent()) {
            my $primaryGroup=getgrgid($gid);
            $groupMembers{$primaryGroup}->{$name}=1;
    }
    while (my($gname,$gpasswd,$gid,$members)=getgrent()) {
            foreach my $member (split / /, $members){
                    $groupMembers{$gname}->{$member}=1;
            }
    }
}
my $membersConcat=join(",",sort keys %{$groupMembers{$groupQuery}});
return "$membersConcat" || "$groupQuery Does have any members";
}
print &expandGroupMembers($arg)."\n";

在UNIX(与GNU/Linux相反)中,有listusers命令。有关listusers,请参阅Solaris手册页。

注意,这个命令是开源家宝项目的一部分。我认为它在GNU/Linux中是缺失的,因为RMS不相信组和权限。: -)

下面的命令将列出属于<your_group_name>的所有用户,但只列出由/etc/group数据库管理的用户,不包括LDAP、NIS等。它也只适用于次要组,它不会列出将该组设置为主要组的用户,因为主要组存储为/etc/passwd.文件中的GID(数字组ID)

awk -F: '/^groupname/ {print $4;}' /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