使用 importlib 导入 pyarmor 混淆代码

Import pyarmor obfuscated code using importlib

假设我有 2 个模块 - 一个已被 PyArmor 混淆。另一个导入混淆模块并使用它:

# obfuscated.py
def run_task(conn):
    conn.send_msg("Here you go")
    print(conn.some_val + 55)
    return 0
# Non obfuscated (user) code
import importlib.util


class conn:
    some_val = 5
    
    def send_msg(msg):
        print(msg)

def main():
    # import obfuscated # This works...but I need to dynamically load it:

    # This does not:
    spec = importlib.util.spec_from_file_location("module.name", r'c:\Users\me\obfuscated.py')
    obfuscated = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(swdl)
    ret = obfuscated.run_task(conn)
    print("from main: ", ret)

if __name__ == "__main__":
    main()

如果我使用 import 导入混淆文件就可以了。但是我需要使用 importlib 来动态导入混淆文件。 importlib 不起作用 - 我得到:

AttributeError: module 'module.name' has no attribute 'obfuscated'

想法是用户可以使用 obfuscated.py 中可用的 API 编写脚本,但需要从其系统上的任何位置加载模块。

有没有办法实现这个?

我想我有一个基于我在这里阅读的方法:https://pyarmor.readthedocs.io/en/latest/mode.html#restrict-mode

我在用户代码和混淆代码之间使用了代理。

  • 用户代码可能会也可能不会被混淆
  • 混淆后的代码明显是被混淆了!
  • 代理不得混淆(为简单起见,我混淆了所有内容,然后将原始 proxy.py 复制到混淆的代理上)

因此,现在用户代码使用 importlib 而不是 obfuscated.py 导入 proxy.py

而代理仅导入 obfuscated.py:

# proxy.py
import obfuscated

我设法以这种方式动态导入模块:

    code = open('c:\Users\me\obfuscated.py','r').read()
    spec = importlib.util.spec_from_loader(package_name,loader=None)
    module = importlib.util.module_from_spec(spec)
    module.__file__ = 'c:\Users\me\obfuscated.py'
    globals_dict = {"__file__":module.__file__}
    exec(code, globals_dict)
    for item in [x for x in globals_dict["__builtins__"] if not x.startswith("_")]:
        setattr(module,item,globals_dict["__builtins__"].get(item))

它从文件中读取代码,启动模块,并最终将变量放入字典中。您可以在 globals_dict["__builtins__"]

中找到该模块的功能