Skip to content

Instantly share code, notes, and snippets.

@ThoenigAdrian
Last active September 3, 2024 12:32
Show Gist options
  • Save ThoenigAdrian/b12bb7e6c438fd4f7a7e56c67a294484 to your computer and use it in GitHub Desktop.
Save ThoenigAdrian/b12bb7e6c438fd4f7a7e56c67a294484 to your computer and use it in GitHub Desktop.
Search process by name ctypes windows - WAAAAY FASTER THAN psutil psutil.process_iter()
import ctypes
import ctypes.wintypes
# Load the required libraries
psapi = ctypes.WinDLL('Psapi.dll')
kernel32 = ctypes.WinDLL('kernel32.dll')
# Define constants
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
MAX_PATH = 260
def get_pids_by_name_fast(process_name):
process_name = process_name.encode('utf-8')
pids = []
# Allocate an array for the process IDs
array_size = 1024
pid_array = (ctypes.wintypes.DWORD * array_size)()
bytes_returned = ctypes.wintypes.DWORD()
# Call EnumProcesses to get the list of process IDs
if not psapi.EnumProcesses(ctypes.byref(pid_array), ctypes.sizeof(pid_array), ctypes.byref(bytes_returned)):
raise ctypes.WinError(ctypes.get_last_error())
# Calculate the number of processes
num_pids = bytes_returned.value // ctypes.sizeof(ctypes.wintypes.DWORD)
# Iterate over all the process IDs
for pid in pid_array[:num_pids]:
# Open the process with necessary privileges
h_process = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
if h_process:
exe_name = (ctypes.c_char * MAX_PATH)()
h_module = ctypes.wintypes.HMODULE()
needed = ctypes.wintypes.DWORD()
# Get the first module, which is the executable
if psapi.EnumProcessModules(h_process, ctypes.byref(h_module), ctypes.sizeof(h_module), ctypes.byref(needed)):
psapi.GetModuleBaseNameA(h_process, h_module, ctypes.byref(exe_name), ctypes.sizeof(exe_name))
if exe_name.value.lower() == process_name.lower():
pids.append(pid)
kernel32.CloseHandle(h_process)
return pids
# Example usage:
process_name = "python.exe"
matching_pids = get_pids_by_name_fast(process_name)
print(f"PIDs for processes named '{process_name}': {matching_pids}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment