如何在Linux(可能还有其他unix)中列出一个组的所有成员?
当前回答
使用Python列出组成员:
import grp;打印grp.getgrnam (GROUP_NAME)[3]”
参见https://docs.python.org/2/library/grp.html
其他回答
下面的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的名称。
lid -g groupname | cut -f1 -d'('
我所做的与上面的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";
下面是一个脚本,返回/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
你可以在一个命令行中完成:
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'
推荐文章
- 有效地测试Linux上的端口是否打开?
- 如何从另一个文件A中删除文件B中出现的行?
- 对以制表符分隔的文件进行排序
- 使用sudo时未找到命令
- 当有命令行参数时,如何使用GDB分析程序的核心转储文件?
- 如何使用查找命令从列表中查找所有具有扩展名的文件?
- 如何强制从另一个SSH会话分离屏幕?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- Linux Bash中双&和分号有什么区别?
- 在SSH会话中查找客户端的IP地址
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Linux删除大小为0的文件
- Spring引导应用程序作为服务
- 如何重定向标准derr和标准输出到不同的文件在同一行脚本?