Given a binary file, such as "Installer.exe", how can I read in the bytes of that file and then execute those bytes?
i.e.
with open('Installer.exe', 'rb') as file:
data = file.read()
some_function_to_execute_bytes(data)
I am aware that it is possible to execute a file using subprocess, such as
import subprocess
subprocess.run('Installer.exe')
but I would like to run a string of bytes no matter how it is obtained (very similar to Possible to execute Python bytecode from a script? question, but the binary file is not Python code).
In my use case, I have a .exe file generated by pyinstaller in a MemoryFS object from pyfilesystem. Notably, a file in a MemoryFS
object cannot be ran at the system level - simply because it does not exist on the file system; it is stored entirely in memory.
I would like a way to be able to read the binary file in memory and execute it. Writing it to a file on the local file system is not acceptable - increased time to perform the write operation, taking up extra file system space, needing more cleanup, etc.
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)