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
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.
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'
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With