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

2

15

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

Alberthaalberti answered 24/3, 2015 at 22:28 Comment(0)
I
30

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.

Ionosphere answered 14/11, 2019 at 22:53 Comment(0)
B
7

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
Bernat answered 25/3, 2015 at 19:49 Comment(4)
What if you don't have root permissions for sudo?Currant
Good point - question was how to check for permissions on a specific user, so it's not a stretch to assume "checker" has root. If I, as a non-root user, want to know permissions/access of another user, I can't see a clear way to do that without asking a) a sysadmin or b) the user....Bernat
Yes, this was something I wanted to do without root, and we couldn't find a solution...Currant
@Currant What if you started by looking at the permissions and user/group ownership of the specific directory, then compare that against the user you're interested in? So if a directory is userA:groupA - with perms drwxrwxr-x, and userB isn't in groupA, then no.Bernat

© 2022 - 2024 — McMap. All rights reserved.