Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if different user has read/write permissions to a file on linux

How can I check if a specific user with no shell assigned can write or read a file ?

As an example we can use apache user... is there any option in touch or any other commands?

Thanks

like image 299
pollus Avatar asked Mar 24 '15 22:03

pollus


2 Answers

The "test" command is designed for this use case.

sudo -u otheruser test -r /path/to/file

will return 0 if otheruser can read the file, or 1 if otheruser cannot read the file. You can run test -r /path/to/file; echo "$?" to view the return code of the test command.

Use test -w to test for write permission and test -x to test for execute permission.

like image 75
Kevin Burke Avatar answered Sep 27 '22 17:09

Kevin Burke


Test Read Permission

Attempt to read the beginning of the file and discard the normal output. You can then look for an empty string (success) or a "Permission denied" message (you can also check for other error messages such as "No such file or directory"). For example:

head -1 /path/to/file 2>&1 > /dev/null | grep 'Permission denied'

Test Write Permission

Use the touch command with the -c (--no-create) option. Combine stdout and stderr and again search for an empty string (success) or an error:

touch -c /path/to/file 2>&1 | grep 'Permission denied'

If you're explicitly testing write access of a directory, be sure to test the directory and not a file contained within, since with the -c option, there's no error condition if the file doesn't exist even in a directory you don't have write access to:

From Wikipedia: touch (Unix)

-c, if the file does not exist, do not create it and do not report this condition

Test As Specific User

The final piece of the puzzle is how to check this as a different user. As root execute the test command as the desired user with "sudo -u [username] [command]" so using your suggested user:

sudo -u apache touch -c /path/to/file 2>&1
like image 35
bgstech Avatar answered Sep 27 '22 18:09

bgstech