执行嵌入在Python脚本中的.exe文件 [英] Execute .exe file embedded in Python script

查看:147
本文介绍了执行嵌入在Python脚本中的.exe文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以base64编码的字符串存储的exe文件加载到内存中并执行而不将其写入磁盘?

How can I load an exe file—stored as a base64 encoded string—into memory and execute it without writing it to disk?

重点是放置某种控制/密码/串行系统,并使用py2exe进行编译.然后我可以随时在代码中执行该嵌入式文件.

The point being, to put some kind of control/password/serial system in place and compile it with py2exe. Then I could execute that embedded file when ever I want in my code.

推荐答案

Python用于执行子进程的所有机制都需要文件名.

All of the mechanisms Python has for executing a child process require a filename.

基础 CreateProcess 函数,因此降低到该级别甚至没有简单的方法.

And so does the underlying CreateProcess function in the Win32 API, so there's not even an easy way around it by dropping down to that level.

通过ZwCreateProcess/此帖子应该是您需要了解的所有内容.如果您不……在SO答案中解释太多了.

There is a way to do this by dropping down to ZwCreateProcess/NtCreateProcess. If you know how to use the low-level NT API, this post should be all you need to understand it. If you don't… it's way too much to explain in an SO answer.

当然,您也可以创建或使用RAM驱动器,甚至可以模拟虚拟文件系统,但是为了避免创建文件而变得有点愚蠢了.

Alternatively, of course, you can create or use a RAM drive, or even simulate a virtual filesystem, but that's getting a little silly as an attempt to avoid creating a file.

因此,正确的答案是将exe写入文件,然后执行该文件.例如,如下所示:

So, the right answer is to write the exe to a file, then execute it. For example, something like this:

fd, path = tempfile.mkstemp(suffix='.exe')
code = base64.b64decode(encoded_code)
os.write(fd, code)
os.fchmod(fd, 0o711)
os.close(fd)
try:
    result = subprocess.call(path)
finally:
    os.remove(path)

这在Windows和* nix上都可以使用,但尚未经过测试,并且至少在一个平台上可能存在错误.

This should work on both Windows and *nix, but it's completely untested, and will probably have bugs on at least one platform.

很显然,如果您想多次执行它,请先remove直到完成后再执行.或者只是使用一些适当的持久性目录,并仅在缺少或过时时才写它.

Obviously, if you want to execute it multiple times, don't remove it until you're done with it. Or just use some appropriate persistent directory, and write it only if it's missing or out of date.

这篇关于执行嵌入在Python脚本中的.exe文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆