Test if a directory is writable by a given UID?

后端 未结 8 1577
一生所求
一生所求 2020-12-14 14:31

We can test if a directory is writable by the uid of the current process:

if [ -w $directory ] ; then echo \'Eureka!\' ; fi

But can anyone

8条回答
  •  执念已碎
    2020-12-14 15:19

    I've written a function can_user_write_to_file which will return 1 if the user passed to it either is the owner of the file/directory, or is member of a group which has write access to that file/directory. If not, the method returns 0.

    ## Method which returns 1 if the user can write to the file or
    ## directory.
    ##
    ## $1 :: user name
    ## $2 :: file
    function can_user_write_to_file() {
      if [[ $# -lt 2 || ! -r $2 ]]; then
        echo 0
        return
      fi
    
      local user_id=$(id -u ${1} 2>/dev/null)
      local file_owner_id=$(stat -c "%u" $2)
      if [[ ${user_id} == ${file_owner_id} ]]; then
        echo 1
        return
      fi
    
      local file_access=$(stat -c "%a" $2)
      local file_group_access=${file_access:1:1}
      local file_group_name=$(stat -c "%G" $2)
      local user_group_list=$(groups $1 2>/dev/null)
    
      if [ ${file_group_access} -ge 6 ]; then
        for el in ${user_group_list-nop}; do
          if [[ "${el}" == ${file_group_name} ]]; then
            echo 1
            return
          fi
        done
      fi
    
      echo 0
    }
    

    To test it, I wrote a wee test function:

    function test_can_user_write_to_file() {
      echo "The file is: $(ls -l $2)"
      echo "User is:" $(groups $1 2>/dev/null)
      echo "User" $1 "can write to" $2 ":" $(can_user_write_to_file $1 $2)
      echo ""
    }
    
    test_can_user_write_to_file root /etc/fstab
    test_can_user_write_to_file invaliduser /etc/motd
    test_can_user_write_to_file torstein /home/torstein/.xsession
    test_can_user_write_to_file torstein /tmp/file-with-only-group-write-access
    

    At least from these tests, the method works as intended considering file ownership and group write access :-)

提交回复
热议问题