Sometimes you just need a boolean test for a given question. In this post we’ll look at answering the question, “Is this user in a given group?” Seems simple enough.
It’s easy to see what groups a user is a member of in a shell:
[code lang=text]
% id
alice@iachieved.it@darthvader:~$ id
uid=1068601116(alice@iachieved.it) gid=1068601115(iachievedit@iachieved.it) groups=1068601115(iachievedit@iachieved.it),1068600513(domain users@iachieved.it),1068601109(linux ssh@iachieved.it),1068601118(application deployment@iachieved.it)
[/code]
Note that Alice is an Active Directory domain user. We want to test whether or not she is a member of the application deployment@iachieved.it
group. We can see this with our eyes in the terminal, but a little scripting is in order. We’ll skip error checking for this first example.
uig.sh
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#!/bin/bash USER=$1 GROUP=$2 # getent returns all of the members of a given group, see # https://en.wikipedia.org/wiki/Getent for examples uig=`getent group "$2" | awk '{split($0,a,":"); print a[4];}'` # IFS (internal field separator) is a gem I frequently forget about IFS="," read -r -a array <<< $uig # Print each entry of our array (members of the group) and then # grep to find if $USER is there if printf '%s\n' ${array[@]} | grep -qP "^${USER}$"; then echo "User $USER IS in group $GROUP" exit 0 fi echo "User $USER IS NOT in group $GROUP" exit -1 |
Let’s take it out for a spin.
[code lang=text]
alice@iachieved.it@darthvader:~$ ./uig.sh `whoami` "linux administrators@iachieved.it"
User alice@iachieved.it IS NOT in group linux administrators@iachieved.it
[/code]
Now let’s test whether or not Alice is in the application deployment@iachieved.it
group:
[code lang=text]
alice@iachieved.it@darthvader:~$ ./uig.sh `whoami` "application deployment@iachieved.it"
User alice@iachieved.it IS in group application deployment@iachieved.it
[/code]
Terrific. This will come in handy in the next blog post.
Let’s clean this up into a function that can be sourced in a script or shell:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash function uig () { if [ $# -ne 2 ]; then return -1; fi USER=$1 GROUP=$2 _uig=`getent group "$2" | awk '{split($0,a,":"); print a[4];}'` IFS="," read -r -a array <<< $_uig if printf '%s\n' ${array[@]} | grep -qP "^${USER}$"; then return 0 fi return -1 } |
[code lang=text]
alice@iachieved.it@darthvader:~$ uig `whoami` "linux ssh@iachieved.it"
alice@iachieved.it@darthvader:~$ echo $?
0
[/code]
Or, the invocation we’re most likely to use:
1 2 3 4 5 6 |
uig `whoami` "linux ssh@iachieved.it" if [ "$?" == 0 ]; then echo "In the group"; else echo "Not in the group"; fi |