开发者

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 ca开发者_高级运维n'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-'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜