Check if a user is in a group

后端 未结 13 2045
梦如初夏
梦如初夏 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:02

    A while ago, I wrote a shell function to check if a user is a member of a group. To maximise portability, I wanted it be POSIX-compatible (while this question is tagged as bash, this function will still work). For performance, I wanted to use builtin shell features as much as possible: the only external command it uses is id, the POSIX-standardised utility for getting data about a user’s identity.

    is_in_group()
    {
      groupname="$1"
      # The second argument is optional -- defaults to current user.
      current_user="$(id -un)"
      user="${2:-$current_user}"
      for group in $(id -Gn "$user") ; do
        if [ "$group" = "$groupname" ]; then
          return 0
        fi
      done
      # If it reaches this point, the user is not in the group.
      return 1
    }
    

    Example usage to test both positive and negative cases – and ensure it handles a non-existent username gracefully:

    g=mail
    userlist="anthony postfix xxx"
    for u in $userlist; do
      if is_in_group "$g" "$u"; then
        printf "%s is in ‘%s’\n" "$u" "$g"
      else
        printf "%s is NOT in ‘%s’\n" "$u" "$g"
      fi
    done
    

    Running the above command prints the following output:

    anthony is NOT in ‘mail’
    postfix is in ‘mail’
    id: ‘xxx’: no such user
    xxx is NOT in ‘mail’
    

    It hasn’t been tested for the case where a group or user has a space or other unusual characters in their name but some research shows that such names are not legal: the POSIX Base Definition for Group Name states that

    To be portable across conforming systems, the value is composed of characters from the portable filename character set.

    The Portable Filename Character Set is specified as the alphanumeric characters, A-Z, a-z, 0-9 along with the period, underscore, and hyphen-minus characters.

提交回复
热议问题