是否有明确定义的方法来检查路径是否是 Python 中的简单 file/folder 名称?
Is there a well-defined way to check if a path is a simple file/folder name in Python?
我正在尝试检查给定的用户提供的字符串是否是一个简单的 file/folder 名称。我计划使用 os.path.join() 将此名称连接到预设的根目录,但我想检测并禁止试图遍历该根目录之外任何地方的路径。
例如,值为 'track001.mp3' 的字符串可以解析为 'root_dir/track001.mp3'。然而,这些应该被检测到并被禁止:
'../other_root_dir/'
'/etc'
'/'
'~'
'subdir/inner_file'
我建议您像往常一样创建路径字符串 假设 用户的行为(例如传递 "simple" 或一致的路径名)。然后我会使用 os.path.expandvars
and os.path.normpath
来获取实际路径名。最后,我会检查以确保实际路径名位于根目录中。类似于:
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.
我正在尝试检查给定的用户提供的字符串是否是一个简单的 file/folder 名称。我计划使用 os.path.join() 将此名称连接到预设的根目录,但我想检测并禁止试图遍历该根目录之外任何地方的路径。
例如,值为 'track001.mp3' 的字符串可以解析为 'root_dir/track001.mp3'。然而,这些应该被检测到并被禁止:
'../other_root_dir/'
'/etc'
'/'
'~'
'subdir/inner_file'
我建议您像往常一样创建路径字符串 假设 用户的行为(例如传递 "simple" 或一致的路径名)。然后我会使用 os.path.expandvars
and os.path.normpath
来获取实际路径名。最后,我会检查以确保实际路径名位于根目录中。类似于:
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.