[英]Is there a well-defined way to check if a path is a simple file/folder name in Python?
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.
我计划使用os.path.join()将这个名称连接到预设的根目录,但是我想检测并禁止试图遍历该根目录之外的任何路径。
For example, a string with the value 'track001.mp3' would be fine, it would resolve to 'root_dir/track001.mp3'. 例如,值为“ track001.mp3”的字符串就可以了,它将解析为“ root_dir / track001.mp3”。 However, these should be detected and disallowed:
但是,应检测并禁止以下操作:
'../other_root_dir/'
'/etc'
'/'
'~'
'subdir/inner_file'
I would advise you to create the path string as you normally would assuming that the user is behaving (eg passing a "simple" or conforming path name). 我建议您像通常假设用户所表现的那样创建路径字符串(例如,传递“简单”或一致的路径名)。 Then I'd use
os.path.expandvars
and os.path.normpath
to get the actual path name. 然后,我将使用
os.path.expandvars
和os.path.normpath
来获取实际的路径名。 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.