Test if a directory is writable by a given UID?

后端 未结 8 1575
一生所求
一生所求 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:14

    You can use sudo to execute the test in your script. For instance:

    sudo -u mysql -H sh -c "if [ -w $directory ] ; then echo 'Eureka' ; fi"
    

    To do this, the user executing the script will need sudo privileges of course.

    If you explicitly need the uid instead of the username, you can also use:

    sudo -u \#42 -H sh -c "if [ -w $directory ] ; then echo 'Eureka' ; fi"
    

    In this case, 42 is the uid of the mysql user. Substitute your own value if needed.

    UPDATE (to support non-sudo-priviledged users)
    To get a bash script to change-users without sudu would be to require the ability to suid ("switch user id"). This, as pointed out by this answer, is a security restriction that requires a hack to work around. Check this blog for an example of "how to" work around it (I haven't tested/tried it, so I can't confirm it's success).

    My recommendation, if possible, would be to write a script in C that is given permission to suid (try chmod 4755 file-name). Then, you can call setuid(#) from the C script to set the current user's id and either continue code-execution from the C application, or have it execute a separate bash script that runs whatever commands you need/want. This is also a pretty hacky method, but as far as non-sudo alternatives it's probably one of the easiest (in my opinion).

提交回复
热议问题