List users in all specified unix groups
I don't known any tool doing this but it is easy to script.
At first get the list of the users on the system, then run groups
on each and at the end, grep
on the desired groups :
getent passwd | sed 's/:.*$//g' | \
while read user; do groups $user; done | \
grep group1 | grep group2
This works for two groups at a time:
getent group dell hp | cut -d: -f 4 | tr , '\n' | sort | uniq -d | sed ':a;$s/\n/, /g;N;ba'
Put it in a function with some modifications and it will handle any number of groups:
grmagic () {
getent group "$@" |
cut -d: -f 4 |
tr , '\n' |
sort |
uniq -dc |
grep "^[[:blank:]]*$#" |
awk '{all = all d $3; d = ", "} END {print all}'
}
Run it:
$ grmagic dell hp
zippy, george, bungle
$ grmagic dell hp rainbow
zippy, bungle
A function consisting mostly of an AWK script:
grmagic () {
getent group "$@" |
awk -F: -v "c=$#" '{
split($4, a, ",");
for (i in a) n[a[i]]++
}
END {
for (i in n)
if (n[i] == c) {
printf d i; d=", "
};
printf "\n" }'
}
Small python script:
#!/usr/bin/python
import subprocess,sys
group={}
for user in sys.argv[1:]:
group[user] = set(subprocess.Popen("id -nG %s"%user, stdout=subprocess.PIPE, shell=True).stdout.read().split())
for g in group[sys.argv[1]] & group[sys.argv[2]]:
print g
Test:
# id user1
uid=1001(user1) gid=1001(user1) groups=1001(user1),1004(us1),1005(dell)
# id user2
uid=1002(user2) gid=1002(user2) groups=1002(user2),1004(us1),1005(dell)
# ./test.py user1 user2
dell
us1