简体   繁体   中英

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.

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-'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM