简体   繁体   English

检查非root用户是否可以访问路径

[英]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.我有一个用 Python(在 Linux 中)编写的安装脚本,它以 root 身份运行,需要检查某些文件是否可以被非 root 用户读取。

For this reason I can't use os.path.exists() or open(filename) (and catch any exceptions).出于这个原因,我不能使用 os.path.exists() 或 open(filename) (并捕获任何异常)。

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.目前我正在考虑检查每个文件的权限位,但唯一的问题是我还必须检查通向文件名的路径上的权限位(目录需要设置 r+x 位),如果我有数千个文件,这可能是一个非常缓慢的过程。

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.编辑:检查文件后,我需要以 root 身份运行脚本,因此不幸的是,删除 root 权限不是一个选项。

You could use os.seteuid to change the effective user to some non-root user.您可以使用os.seteuid将有效用户更改为某个非 root 用户。 Then try opening the file.然后尝试打开文件。 An IOError will be raised if permission is denied.如果权限被拒绝,将IOError

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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