简体   繁体   中英

Execute .exe file embedded in Python script

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

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.

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.

encode exe:

import base64
#encode exe file in base64 data

with open("Sample.exe", 'rb') as f:
    read_exe_to_basae64 = base64.b64encode(f.read())
    

#encoded data will be like (really big text, don't worry) for e.g.: 
b'TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAyAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAAA9AHveeWEVjXlhFY15YRWN+n0bjXhhFY0QfhyNfmEVjZB+GI14YRWNUmljaHlhFY0AAAAAAAAAAAAAAA'

#decode exe file:

with open("Sample2.exe", 'wb') as f: 
    f.write(base64.b64decode(read_exe_to_basae64))

exe file will be created in folder. If you don't want users to see it, just decode it in any random folder and delete it after use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM