Execute .exe file embedded in Python script

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.

Leave a Comment