我想根据不受信任的用户输入动态导入模块,并确信我将导入的子模块来自特定的受信任模块目录。
我打算按以下方式处理用户输入:
import importlib
submodule_name = user_input.split(".")[0]
# Are the 2 following lines safe ? (considering I trust all code in `trusted_directory`)
imported_module = importlib.import_module(f"trusted_directory.{submodule_name}")
imported_module.main()
trusted_directory
将包含我自己编写的 pyhon 模块,每个模块都实现一个 main()
函数。我主要担心两件事:
user_input
的值是否会导致导入trusted_directory
之外的模块?更一般地说,我的方法安全吗?你能找到摆脱
trustred_directory
的方法吗?有没有我没有找到的推荐的 Python 导入卫生方法?
我四处寻找有关Python中绝对/相对导入的规范,只能找到PEP 323。从我对这个规范的理解来看,我的方法似乎是安全的,但我担心我错过了规范的其他重要部分。
你不能依赖用户来把事情做好,所以,这并不重要。您最终将得到一个存在的模块列表,并且只有与列表中的某些内容匹配的用户输入才会通过加载模块的条件。基本上,由于您必须对模块甚至不存在的事实采取一些措施,因此它本质上会负责加载远程模块,因为远程模块不会出现在列表中。
类似这样的:
import importlib, glob, os
CWD = os.getcwd()
os.chdir('trusted_directory')
if user_input in glob.glob('*.py'):
imported_module = importlib.import_module(f"trusted_directory.{submodule_name}")
imported_module.main()
os.chdir(CWD)