From 3ebd8b20a4ef021923539856465784270023c3f0 Mon Sep 17 00:00:00 2001 From: Admin Date: Wed, 28 Jan 2026 17:34:38 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=B7=BB=E5=8A=A0=E5=8F=97=E9=99=90?= =?UTF-8?q?=E7=9A=84=20=5F=5Fimport=5F=5F=20=E5=87=BD=E6=95=B0=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E7=99=BD=E5=90=8D=E5=8D=95=E6=A8=A1=E5=9D=97=E5=AF=BC?= =?UTF-8?q?=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 解决脚本执行时 KeyError: '__import__' 错误 --- backend/app/services/script_executor.py | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/backend/app/services/script_executor.py b/backend/app/services/script_executor.py index 03ad805..8fc1279 100644 --- a/backend/app/services/script_executor.py +++ b/backend/app/services/script_executor.py @@ -156,9 +156,30 @@ class ScriptExecutor: import random import hashlib import base64 + import time + import collections from datetime import datetime, date, timedelta from urllib.parse import urlencode, quote, unquote + # 允许导入的模块白名单 + ALLOWED_MODULES = { + 'json': json, + 're': re, + 'math': math, + 'random': random, + 'hashlib': hashlib, + 'base64': base64, + 'time': time, + 'datetime': __import__('datetime'), + 'collections': collections, + } + + def safe_import(name, globals=None, locals=None, fromlist=(), level=0): + """受限的 import 函数""" + if name in ALLOWED_MODULES: + return ALLOWED_MODULES[name] + raise ImportError(f"不允许导入模块: {name}。已内置可用: {', '.join(ALLOWED_MODULES.keys())}") + # 安全的内置函数 safe_builtins = {name: getattr(__builtins__, name, None) for name in ALLOWED_BUILTINS @@ -170,12 +191,16 @@ class ScriptExecutor: for name in ALLOWED_BUILTINS if name in __builtins__} + # 添加受限的 __import__ + safe_builtins['__import__'] = safe_import + # 添加常用异常 safe_builtins['Exception'] = Exception safe_builtins['ValueError'] = ValueError safe_builtins['TypeError'] = TypeError safe_builtins['KeyError'] = KeyError safe_builtins['IndexError'] = IndexError + safe_builtins['ImportError'] = ImportError return { '__builtins__': safe_builtins, @@ -215,6 +240,7 @@ class ScriptExecutor: 'datetime': datetime, 'date': date, 'timedelta': timedelta, + 'time': time, 'urlencode': urlencode, 'quote': quote, 'unquote': unquote,