Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if path accessible by non-root user

I have an installation script written in Python (in Linux) that runs as root and needs to check whether certain files are readable by a non-root user.

For this reason I can't use os.path.exists() or open(filename) (and catch any exceptions).

Currently I'm thinking of checking the permission bit on each of the files, but the only problem is that I will have to check the permission bits on the path leading up to the filename as well (directories need r+x bits set), which could be very slow process if I have thousands of files.

Is my solution the best one, or are there better alternatives?

edit: I will need the script run as root after the files are checked, so dropping root permissions is not an option unfortunately.

like image 482
14 revs, 12 users 16% Avatar asked Jul 08 '11 14:07

14 revs, 12 users 16%


People also ask

What directory is typically used to store the files of non-root users?

D:\ is used to store data such as documents, images, etc. Essentially D:\ store any data of value.

How do I give permission to non-root user?

Resolution. sudo (superuser do) allows you to configure non-root users to run root level commands without being root. Access can be given by the root level administrator through configuration of the /etc/sudoers file.

How do you check if a user has access to a 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.


1 Answers

You could use os.seteuid to change the effective user to some non-root user. Then try opening the file. An IOError will be raised if permission is denied.

import os
os.seteuid(65534)  # user 65534 is `nobody`
filename='/etc/passwd-'
try:
    open(filename,'r')
except IOError as err:
    print(err)

# [Errno 13] Permission denied: '/etc/passwd-'
like image 53
unutbu Avatar answered Oct 18 '22 06:10

unutbu