12

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

Kevin Burke
  • 61,194
  • 76
  • 188
  • 305
pollus
  • 131
  • 1
  • 1
  • 3

2 Answers2

28

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.

Kevin Burke
  • 61,194
  • 76
  • 188
  • 305
6

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
bgstech
  • 624
  • 6
  • 12
  • 4
    What if you don't have root permissions for sudo? – Siwel Aug 04 '19 at 23:37
  • 2
    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.... – bgstech Nov 06 '19 at 20:07
  • 3
    Yes, this was something I wanted to do without root, and we couldn't find a solution... – Siwel Nov 06 '19 at 20:09
  • @Siwel 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. – bgstech Nov 08 '19 at 19:27