You can inject a Python interpreter into a target process using Pymem.inject_python_interpreter(). This method dynamically locates the correct python.dll for your environment, injects it into the target process, and registers the py_run_simple_string function, allowing you to execute Python code within that process's memory space.
To execute arbitrary Python code after injection, use Pymem.inject_python_shellcode(shellcode). This method performs the following steps:
- Uses
VirtualAllocEx to allocate memory in the target process. - Writes your Python code (as a string) into the allocated space.
- Executes
py_run_simple_string to interpret the code within the target process.
from pymem import Pymem
import os
import subprocess
# 1. Start a target process
notepad = subprocess.Popen(['notepad.exe'])
# 2. Attach Pymem to the process
pm = Pymem('notepad.exe')
# 3. Inject the Python interpreter and register py_run_simple_string
pm.inject_python_interpreter()
# 4. Prepare and inject Python shellcode
filepath = os.path.join(os.path.abspath('.'), 'pymem_injection.txt')
filepath = filepath.replace("\", "\\\\")
shellcode = """
f = open("{}", "w+")
f.write("pymem_injection")
f.close()
""".format(filepath)
pm.inject_python_shellcode(shellcode)
# 5. Cleanup
notepad.kill()