有没有一种定义明确的方法来检查路径是否是Python中的简单文件/文件夹名称? [英] Is there a well-defined way to check if a path is a simple file/folder name in Python?

查看:79
本文介绍了有没有一种定义明确的方法来检查路径是否是Python中的简单文件/文件夹名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查给定的用户提供的字符串是否是简单的文件/文件夹名称.我打算使用os.path.join()将这个名称连接到预设的根目录,但是我想检测并禁止试图遍历该根目录之外的任何路径.

I'm trying to check if a given user-supplied string is a simple file/folder name. I plan on using os.path.join() to concatenate this name to a preset root directory, but I want to detect and prohibit paths that try to traverse anywhere outside of that root directory.

例如,值为'track001.mp3'的字符串就可以了,它将解析为'root_dir/track001.mp3'.但是,应该检测并禁止这些操作:

For example, a string with the value 'track001.mp3' would be fine, it would resolve to 'root_dir/track001.mp3'. However, these should be detected and disallowed:

'../other_root_dir/'
'/etc'
'/'
'~'
'subdir/inner_file'

推荐答案

我建议您像通常假设那样,创建路径字符串(例如,传递用户的行为)(例如,传递简单"或符合要求的路径名).然后,我将使用 os.path.expandvars os.path.normpath 来获取实际的路径名.最后,我将检查以确保实际的路径名位于根目录中.像这样:

I would advise you to create the path string as you normally would assuming that the user is behaving (e.g. passing a "simple" or conforming path name). Then I'd use os.path.expandvars and os.path.normpath to get the actual path name. Finally, I'd check to make sure that the actual path name resides within the root directory. Something like:

from os.path import expandvars, normpath, join

ROOT_DIR = 'root_dir'

user_path = 'some_path'
test_path = normpath(expandvars(join(ROOT_DIR, user_path)))

expected_prefix = normpath(ROOT_DIR)
if not test_path.startswith(expected_prefix):
    raise ValueError(f'Invalid path "{user_path}"')  # python3.6 f-string.

这篇关于有没有一种定义明确的方法来检查路径是否是Python中的简单文件/文件夹名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆