Check if a user is in a group

后端 未结 13 1904
梦如初夏
梦如初夏 2021-01-31 02:42

I have a server running where I use php to run a bash script to verify certain information of a user. For example, I have a webhosting server set up, and in order to be able to

13条回答
  •  佛祖请我去吃肉
    2021-01-31 03:00

    Here's mine.

    First the long version

    #!/bin/bash
    if [[ $# -eq 0 ]]
    then
      echo "Usage: $0 [-v] user group"
      echo ""
      echo "  -v verbose. Outputs a sentence for humans."
      echo ""
      echo "Example:"
      echo ""
      echo "  ingroup wilma sudo && echo Wilma has superpowers"
      exit 2
    fi
    
    if [[ "$1" == "-v" ]]
    then
      verbose=1
      shift
    fi
    
    user=$1
    grp=$2
    # Get groups output
    grps=$(groups $user)
    # Create a regexp. Note that we must create the regexp in a var
    # because it's the only way to allow for spaces in the regexp.
    # Strangely we provide this var unquoted when using it; even 
    # though it has spaces.
    re="^.*:.* $2 "
    if [[ "$grps" =~ $re ]]
    then
      [[ -n "$verbose" ]] && echo "$user is in group $grp"
      # Success error code
      exit 0
    else
      [[ -n "$verbose" ]] && echo "$user is not in group $grp"
      # Fail error code
      exit 1
    fi
    

    Want a shorter version as a function?

    ingroup() {
      re="^.*:.* $2 "
      [[ "$(groups $1) " =~ $re ]] || return 1
    }
    

    Tests

    # Basic positive test
    $ ingroup -v wilma sudo && echo 'and therefore is cool'
    wilma is in group sudo
    and therefore is cool
    
    # Basic negative test
    $ ingroup -v wilma myprivateclub || echo 'sorry bout that'
    wilma is not in group sudo
    sorry bout that
    
    # Test with hyphens in the group name
    $ ingroup -v wilma systemd-journal
    wilma is in group systemd-journal
    
    # If the group does not exist, it's a negative
    $ ingroup -v wilma somewronggroup
    wilma is not in group somewronggroup
    

提交回复
热议问题