fix: 添加受限的 __import__ 函数支持白名单模块导入
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
解决脚本执行时 KeyError: '__import__' 错误
This commit is contained in:
@@ -156,9 +156,30 @@ class ScriptExecutor:
|
|||||||
import random
|
import random
|
||||||
import hashlib
|
import hashlib
|
||||||
import base64
|
import base64
|
||||||
|
import time
|
||||||
|
import collections
|
||||||
from datetime import datetime, date, timedelta
|
from datetime import datetime, date, timedelta
|
||||||
from urllib.parse import urlencode, quote, unquote
|
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)
|
safe_builtins = {name: getattr(__builtins__, name, None)
|
||||||
for name in ALLOWED_BUILTINS
|
for name in ALLOWED_BUILTINS
|
||||||
@@ -170,12 +191,16 @@ class ScriptExecutor:
|
|||||||
for name in ALLOWED_BUILTINS
|
for name in ALLOWED_BUILTINS
|
||||||
if name in __builtins__}
|
if name in __builtins__}
|
||||||
|
|
||||||
|
# 添加受限的 __import__
|
||||||
|
safe_builtins['__import__'] = safe_import
|
||||||
|
|
||||||
# 添加常用异常
|
# 添加常用异常
|
||||||
safe_builtins['Exception'] = Exception
|
safe_builtins['Exception'] = Exception
|
||||||
safe_builtins['ValueError'] = ValueError
|
safe_builtins['ValueError'] = ValueError
|
||||||
safe_builtins['TypeError'] = TypeError
|
safe_builtins['TypeError'] = TypeError
|
||||||
safe_builtins['KeyError'] = KeyError
|
safe_builtins['KeyError'] = KeyError
|
||||||
safe_builtins['IndexError'] = IndexError
|
safe_builtins['IndexError'] = IndexError
|
||||||
|
safe_builtins['ImportError'] = ImportError
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'__builtins__': safe_builtins,
|
'__builtins__': safe_builtins,
|
||||||
@@ -215,6 +240,7 @@ class ScriptExecutor:
|
|||||||
'datetime': datetime,
|
'datetime': datetime,
|
||||||
'date': date,
|
'date': date,
|
||||||
'timedelta': timedelta,
|
'timedelta': timedelta,
|
||||||
|
'time': time,
|
||||||
'urlencode': urlencode,
|
'urlencode': urlencode,
|
||||||
'quote': quote,
|
'quote': quote,
|
||||||
'unquote': unquote,
|
'unquote': unquote,
|
||||||
|
|||||||
Reference in New Issue
Block a user