首页 > 解决方案 > 从 .exe 文件在 Python 中执行字节字符串

问题描述

给定一个二进制文件,例如“Installer.exe”,我如何读取该文件的字节然后执行这些字节?

IE

with open('Installer.exe', 'rb') as file:
    data = file.read()
some_function_to_execute_bytes(data)

我知道可以使用子进程执行文件,例如

import subprocess

subprocess.run('Installer.exe')

但我想运行一串字节,不管它是如何获得的(非常类似于可能从脚本执行 Python 字节码?问题,但二进制文件不是Python 代码)。

在我的用例中,我有一个由py ​​installer在 pyfilesystem 的MemoryFS对象中生成的 .exe 文件。值得注意的是,对象中的文件不能在系统级别运行——仅仅是因为它不存在于文件系统中;它完全存储在内存中。MemoryFS

我想要一种能够读取内存中的二进制文件并执行它的方法。将其写入本地文件系统上的文件是不可接受的 - 增加了执行写入操作的时间、占用额外的文件系统空间、需要更多清理等。

from fs.memoryfs import MemoryFS
from fs.osfs import OSFS
from fs.copy import copy_file

external_path = 'some/external/location/that/should/not/run/binary/files/Installer.exe'
external_fs = OSFS('//external/server')
in_memory_fs = MemoryFS()
copy_file(external_fs, external_path, in_memory_fs, 'Installer.exe')

data = in_memory_fs.readbytes('Installer.exe')
some_function_to_execute_bytes(data)

标签: pythonwindowsbinaryexepyfilesystem

解决方案


推荐阅读