Execute .exe file embedded in Python script

我与影子孤独终老i 提交于 2019-12-01 06:31:46

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

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.

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.

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.

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)

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!