gpt4 book ai didi

python - 如何检查一个目录是否是另一个目录的子目录

转载 作者:IT老高 更新时间:2023-10-28 21:48:50 27 4
gpt4 key购买 nike

我喜欢用 Python 编写一个模板系统,它允许包含文件。

例如

    This is a template    You can safely include files with safe_include`othertemplate.rst`

As you know, including files might be dangerous. For example, if I use the template system in a web application which allows users to create their own templates, they might do something like

I want your passwords: safe_include`/etc/password`

So therefore, I have to restrict the inclusion of files to files which are for example in a certain subdirectory (e.g. /home/user/templates)

The question is now: How can I check, whether /home/user/templates/includes/inc1.rst is in a subdirectory of /home/user/templates?

Would the following code work and be secure?

import os.path

def in_directory(file, directory, allow_symlink = False):
#make both absolute
directory = os.path.abspath(directory)
file = os.path.abspath(file)

#check whether file is a symbolic link, if yes, return false if they are not allowed
if not allow_symlink and os.path.islink(file):
return False

#return true, if the common prefix of both is equal to directory
#e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
return os.path.commonprefix([file, directory]) == directory

只要 allow_symlink 为 False,我认为它应该是安全的。如果用户能够创建此类链接,则允许符号链接(symbolic link)当然会使其不安全。

更新 - 解决方案如果中间目录是符号链接(symbolic link),则上面的代码不起作用。为了防止这种情况,您必须使用 realpath 而不是 abspath

更新:在目录后面添加/以解决 commonprefix() Reorx 指出的问题。

这也使得 allow_symlink 变得不必要,因为符号链接(symbolic link)会扩展到它们的真实目标

import os.path

def in_directory(file, directory):
#make both absolute
directory = os.path.join(os.path.realpath(directory), '')
file = os.path.realpath(file)

#return true, if the common prefix of both is equal to directory
#e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
return os.path.commonprefix([file, directory]) == directory

最佳答案

Python 3 的 pathlib 模块通过它的 Path.parents 使这一切变得简单明了。属性。例如:

from pathlib import Path

root = Path('/path/to/root')
child = root / 'some' / 'child' / 'dir'
other = Path('/some/other/path')

然后:

>>> root in child.parents
True
>>> other in child.parents
False

关于python - 如何检查一个目录是否是另一个目录的子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3812849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com