def DLLs(): import win32api import win32process EvidenceOfSandbox = [] sandboxDLLs = ["sbiedll.dll","dbghelp.dll","api_log.dll","dir_watch.dll","pstorec.dll","vmcheck.dll","wpespy.dll"] allPids = win32process.EnumProcesses() for pid in allPids: try: hProcess = win32api.OpenProcess(0x0410, 0, pid) try: curProcessDLLs = win32process.EnumProcessModules(hProcess) for dll in curProcessDLLs: dllName = str(win32process.GetModuleFileNameEx(hProcess, dll)).lower() for sandboxDLL in sandboxDLLs: if sandboxDLL in dllName: if dllName not in EvidenceOfSandbox: EvidenceOfSandbox.append(dllName) finally: win32api.CloseHandle(hProcess) except: pass if EvidenceOfSandbox: return True else: return False
def get_process_by_name(process_name): """Finds the process id of the given process name and returns the process id and its base address.""" process_name = process_name.lower() # Enumerate all processes processes = win32process.EnumProcesses() for process_id in processes: # If process_id is the same as this program, skip it if process_id == -1: continue # Try to read the process memory try: h_process = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, True, process_id) # Try to read the modules of the process try: # modules is an array of base addresses of each module modules = win32process.EnumProcessModules(h_process) for base_address in modules: # Get the name of the module name = str(win32process.GetModuleFileNameEx(h_process, base_address)) # Compare it to the name of your program if name.lower().find(process_name) != -1: return process_id, base_address finally: win32api.CloseHandle(h_process) except: pass
def __init__(self, pid): ph = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) token = win32security.OpenProcessToken(ph, win32con.TOKEN_QUERY) sid, attr = win32security.GetTokenInformation(token, ntsecuritycon.TokenUser) (username, proc_domain, proc_type) = win32security.LookupAccountSid(None, sid) exes = [] modules = [] for module in win32process.EnumProcessModules(ph): fn = win32process.GetModuleFileNameEx(ph, module) if win_exec_re.search(fn): exes.append(fn) else: modules.append(fn) # gross but...eh if not exes: nondll = [] for mod in modules: if not win_dll_re.search(mod): nondll.append(mod) if nondll: exes.append(nondll[0]) super(WindowsProcess, self).__init__(pid, string.join(exes, ' '), username)
def GetProcessIdByName(procname): ''' Try and get pid for a process by name. ''' ourPid = -1 procname = procname.lower() try: ourPid = win32api.GetCurrentProcessId() except: pass pids = win32process.EnumProcesses() for pid in pids: if ourPid == pid: continue try: hPid = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) try: mids = win32process.EnumProcessModules(hPid) for mid in mids: name = str(win32process.GetModuleFileNameEx(hPid, mid)) if name.lower().find(procname) != -1: return pid finally: win32api.CloseHandle(hPid) except: pass return None
def __init__(self): self.PID = self.get_client_pid("One Finger Death Punch.exe") # process = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid) # OpenProcess = windll.kernel32.OpenProcess self.ReadProcessMemory = windll.kernel32.ReadProcessMemory # FindWindowA = windll.user32.FindWindowA # GetWindowThreadProcessId = windll.user32.GetWindowThreadProcessId self.PROCESS_ALL_ACCESS = 0x1F0FFF #self.HWND = win32ui.FindWindow(None, u"One Finger Death punch").GetSafeHwnd() #self.PID = win32process.GetWindowThreadProcessId(HWND)[1] self.processHandle = ctypes.windll.kernel32.OpenProcess( self.PROCESS_ALL_ACCESS, False, self.PID) #print(f"HWND: {self.HWND}") print(f"PID: {self.PID}") print(f"PROCESS: {self.processHandle}") # Open process for reading & writing: self.BaseAddress = win32process.EnumProcessModules( self.processHandle)[0] print("Base memory address", hex(self.BaseAddress)) # Read out the app base (this is not the program / module base, the 'app' is just a huge object): self.appBase = c_int() self.numRead = c_int() game_memory_address = 0x00330000 self.game = c_int() self.ReadProcessMemory(self.processHandle, self.BaseAddress + game_memory_address, byref(self.game), 4, byref(self.numRead)) print("Game memory address", hex(self.game.value))
def isDelphi(pid): h = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) for mod in [win32process.GetModuleFileNameEx(h, x) for x in win32process.EnumProcessModules(h)]: if 'delphi32.exe' in mod: return True return False
def KRModify(self, KRHDID): self.KRHDID = KRHDID if not KRHDID: self.showMSG.setStyleSheet('color:red;') self.showMSG.setText(u'Kingdom Rush HD 未启动 请先启动游戏') self.showChange.setText('') for i in self.widgetList: i.setEnabled(False) else: self.showMSG.setStyleSheet('color:black;') self.showMSG.setText(u'Kingdom Rush HD 已运行') for i in self.widgetList: i.setEnabled(True) PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF) _, pid = win32process.GetWindowThreadProcessId(self.KRHDID) self.phand = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, pid) moduleHdList = win32process.EnumProcessModules(self.phand) for moduleHd in moduleHdList: moduleName = win32process.GetModuleFileNameEx(self.phand, moduleHd) if "mono.dll" in moduleName: break self.moduleHd = moduleHd self.checkTotalWave = checkTotalWave(self, phand=self.phand, moduleHd=self.moduleHd) self.checkTotalWave.totalWave.connect(self.refreshWave) self.checkTotalWave.start()
def _get_base_address(self): process_all_access = 0x1F0FFF process_handle = win32api.OpenProcess(process_all_access, False, self.pid) modules = win32process.EnumProcessModules(process_handle) process_handle.close() base_addr = modules[0] return base_addr
def get_module_addr(process, name): ''' get address of module by name that is a member of process ''' modules = win32process.EnumProcessModules(process) for m in modules: if name in str(win32process.GetModuleFileNameEx(process, m)): return m
def get_mhs(self): if not self.mhs: if self.get_ph(): try: mhs = win32process.EnumProcessModules(self.get_ph()) self.mhs = list(mhs) except: pass return self.mhs
def print_module_names(process): ''' just to help find names ''' modules = win32process.EnumProcessModules(process) for n, m in enumerate(modules): print( str(n) + '-' + hex(m) + '-' + win32process.GetModuleFileNameEx(process, m))
def GetProcessModules(pid): handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid) hModule = win32process.EnumProcessModules(handle) temp = [] for i in hModule: temp.append( [hex(i), debugfile(win32process.GetModuleFileNameEx(handle, i))]) win32api.CloseHandle(handle) return temp
def get_spel2_module(self): module_handles = win32process.EnumProcessModules(self.proc_handle) for module_handle in module_handles: module_filename = Path( win32process.GetModuleFileNameEx(self.proc_handle, module_handle)) if module_filename.name == "Spel2.exe": return module_handle return None
def enderecoBase(): PROCESS_ALL_ACCESS = 0x1F0FFF for proc in psutil.process_iter(): if proc.name() == 'ac_client.exe': pid = proc.pid PROCESS_ALL_ACCESS = 0x1F0FFF processHandle = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, pid) modules = win32process.EnumProcessModules(processHandle) processHandle.close() base_addr = modules[0] return base_addr
def calculate_mono_address(pid): phandle = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, 0, pid) mono_addr = None for module in win32process.EnumProcessModules(phandle): path = win32process.GetModuleFileNameEx(phandle, module) mod_name = path.split('\\')[-1] if mod_name == 'mono.dll': #print(mod_name, hex(module)) mono_addr = module return mono_addr, phandle
def _print_process_pages(self, process): ''' Prints the addresses of all executable memory pages for the specified process. Inspired by similar examples at: https://code.activestate.com/lists/python-tutor/111100/ and discussion of building a Windows debugger in: Gray Hat Python by Justin Seitz (2009) https://nostarch.com/ghpython.htm ''' header = 'Executable memory pages for %s (PID: %s)' % (process.name(), process.pid) print(header) print('=' * len(header)) # Open process handle = self._open_process(PROCESS_ALL_ACCESS, False, process.pid) if not handle: print('[Unable to access memory pages for process %s]' % process.pid) return # Get the process modules -- returns page addresses modules = win32process.EnumProcessModules(handle) # Initialize the data structure that will hold our result mbi = MEMORY_BASIC_INFORMATION() # For each memory address returned, get its permissions for address in modules: if self._virtual_query_ex(handle, address, ctypes.byref(mbi), ctypes.sizeof(mbi)) < ctypes.sizeof(mbi): # If for some reason we can't query # the page, note it and move on print('[Bad VirtualQueryEx for 0x%x!]' % address) continue # Get the protection flags for this # piece of allocated memory flags = mbi.AllocationProtect # Check for executable flags -- flags found at: # https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants if flags & (0x10 | 0x20 | 0x40 | 0x80): # If executable, print its location print('Page address:', hex(mbi.BaseAddress)) print()
def listProcessModules(pid): hprocess = None modules = [] try: hprocess = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid) moduleinfo = win32process.EnumProcessModules(hprocess) for module in moduleinfo: modulefile = win32process.GetModuleFileNameEx(hprocess, module) modules.append(modulefile) return modules except: return modules finally: if hprocess: win32api.CloseHandle(hprocess)
def test2(): allPIDs = win32process.EnumProcesses() for PID in allPIDs: try: hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, PID) hProcessFirstModule = win32process.EnumProcessModules(hProcess)[0] currentprocessname = os.path.split( win32process.GetModuleFileNameEx(hProcess, hProcessFirstModule))[1] if 'QQ.exe' == currentprocessname: print PID except Exception, e: pass #print PID, '\t', e[0], '\t', e[1], '\t', e[2]
def find_process_pids(porcess_name): pids = [] for pid in win32process.EnumProcesses(): try: hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid) hProcessFirstModule = win32process.EnumProcessModules(hProcess)[0] processName = os.path.basename( win32process.GetModuleFileNameEx(hProcess, hProcessFirstModule)) if processName.find(porcess_name) >= 0: pids.append(pid) except Exception, e: # print "on list_process(): ", e # traceback.print_exc() pass
def get_data_from_memory_for_dices(adress, p_pid): PROCESS_ALL_ACCESS = 0x1F0FFF processHandle = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, p_pid) modules = win32process.EnumProcessModules(processHandle) processHandle.close() for module in modules: adress2 = int(adress, 16) result = (read_process_memory(p_pid, adress2, 0, False)) result2 = result.to_bytes(4, 'little') #print(result2) try: check = result2.decode("utf-8") except UnicodeDecodeError: continue return check
def __init__(self, process_name='', pid=None): self._handle = None self._modules = [] self._base_address = 0 self._pid = pid if not self._pid: c = wmi.WMI() for process in c.Win32_Process(): if process.Name == process_name: self._pid = process.ProcessId break if self._pid: self._handle = windll.kernel32.OpenProcess(0x1F0FFF, False, self._pid) self._modules = win32process.EnumProcessModules(self._handle) self._base_address = self._modules[0]
def __init__(self, *args, **kwargs): #-------------------Basic Windows-------------------------------------- self.window = tk.Tk() tk.Frame.__init__(self, self.window, *args, **kwargs) self.build_gui() #--------------------Mem----------------------------------------------- self._pid = self.pid() if self._pid == -1: messagebox.showinfo("Error", "Did not find the pid") exit() #以最高权限打开进程 self._p = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, self._pid) #加载内核模块 self._md = c.windll.LoadLibrary(r'C:\Windows\System32\kernel32') self.module = win32process.EnumProcessModules(self._p)[0]
def get_pids(name): '''get pids of a process''' os_type = platform.system() if os_type in ('Linux', 'Darwin'): s_cmd = "/bin/ps auxww | grep %s | grep -v grep | awk '{print $2}'" % name status, result = getso(s_cmd) print(status, result) if status == 0 and result: return ' '.join(result.split()).split(' ') # list else: return [] elif os_type == 'Windows': if type(name) == int: str_cmd = "netstat -ano|find \"%s\"" % name try: result = os.popen(str_cmd, 'r').read() result = result.split('\n')[0].strip() if result.find('WAIT') != -1: return 0 pid = int(result[result.rfind(' '):].strip()) return [pid] except Exception, e: return 0 else: import win32con import win32api import win32process pids = [] for pid in win32process.EnumProcesses(): try: hProcess = win32api.OpenProcess( win32con.PROCESS_ALL_ACCESS, False, pid) hProcessFirstModule = win32process.EnumProcessModules( hProcess)[0] processName = os.path.splitext( os.path.split( win32process.GetModuleFileNameEx( hProcess, hProcessFirstModule))[1])[0] if processName == name: pids.append(pid) except Exception, e: pass return pids
def getProcessDependModuleFileNamesByPid(pid: int): if platform.system().lower() == 'windows': import win32process import win32api import win32con import win32com import win32com.client handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid) handleModules = win32process.EnumProcessModules(handle) handleModulesCount = len(handleModules) moduleIndex = 0 # 0 - executable itself for moduleIndex in range(handleModulesCount): moduleHandle = handleModules[moduleIndex] moduleFileName = win32process.GetModuleFileNameEx(handle, moduleHandle) yield moduleFileName else: raise RuntimeError(f'This "{platform.system()}" platform does not supported.')
def check_in_memory_for_user_data_and_get_true_base_memory(fourLetters, p_pid): PROCESS_ALL_ACCESS = 0x1F0FFF processHandle = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, p_pid) modules = win32process.EnumProcessModules(processHandle) processHandle.close() #print(modules) for module in modules: adress2 = module + int('7D28D0', 16) result = (read_process_memory(p_pid, adress2, 0, False)) result2 = result.to_bytes(4, 'little') #print(result2) try: check = result2.decode("utf-8") except UnicodeDecodeError: #print(result2) continue if check == fourLetters: print(module) return module
def kill_process(name): for pid in win32process.EnumProcesses(): # do try not to kill yourself if pid == win32api.GetCurrentProcessId(): continue try: p = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ | win32con.PROCESS_TERMINATE, False, pid) except: continue if not p: continue try: hl = win32process.EnumProcessModules(p) except: win32api.CloseHandle(p) continue h = hl[0] pname = win32process.GetModuleFileNameEx(p, h) root, pname = os.path.split(pname) #print name, pname if compare(name, pname): #print "KILL", pname win32api.TerminateProcess(p, 0) win32api.CloseHandle(p) return True win32api.CloseHandle(p) return False
def foo(): # win32api.ExitWindows(win32con.EWX_FORCE | win32con.EWX_SHUTDOWN) try: # win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, win32process.GetCurrentProcess()) processes = win32process.EnumProcesses() for process in processes: try: hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, process) if not hProcess: continue print 'open %d success' % process processModules = win32process.EnumProcessModules(hProcess) for processModule in processModules: print 'processModule %d' % processModule # print 'moduleFileName %s' % str(GetModuleFileNameEx(hProcess, processModule)) # print 'moduleFileName %s' % '' print 'haha' except Exception as e: # print 'open %d failed' % process continue # print processes except Exception as e: print process print e
def get_by_name(cls, process_name: str) -> "Process": """Finds a process by name and returns a Process object.""" for process_id in win32process.EnumProcesses(): # If process_id is the same as this program, skip it if process_id == -1: continue handle = None # Try to read the process memory try: handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, True, process_id) except: continue else: # iterate over an array of base addresses of each module for base_address in win32process.EnumProcessModules(handle): # Get the name of the module current_name = str( win32process.GetModuleFileNameEx(handle, base_address)) # compare it if process_name.casefold() in current_name.casefold(): logging.debug( f"Base address of {process_name} ({process_id}): {hex(base_address)}" ) return cls(process_id, process_name, base_address) finally: if handle: # close the handle as we don't need it anymore win32api.CloseHandle(handle) raise Exception(f"{process_name} could not be found.")
def __init__(self, window_title): OpenProcess = windll.kernel32.OpenProcess self.ReadProcessMemory = windll.kernel32.ReadProcessMemory SIZE_T = c_size_t self.ReadProcessMemory.argtypes = [ HANDLE, LPCVOID, LPVOID, SIZE_T, POINTER(SIZE_T) ] FindWindowA = windll.user32.FindWindowA GetWindowThreadProcessId = windll.user32.GetWindowThreadProcessId PROCESS_ALL_ACCESS = 0x1F0FFF HWND = win32ui.FindWindow(None, window_title).GetSafeHwnd() PID = win32process.GetWindowThreadProcessId(HWND)[1] self.processHandle = ctypes.windll.kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, PID) values = win32process.EnumProcessModules(self.processHandle) self.pointer_dict = dict() self.address_dict = dict() for value in values: name = ntpath.basename( win32process.GetModuleFileNameEx(self.processHandle, value)) self.pointer_dict[name] = value
import sys import win32process from win32com.client import Dispatch parser = Dispatch("Scripting.FileSystemObject") pyVer = "{}{}".format(sys.version_info[0],sys.version_info[1]) pyLibName = "python{}.dll".format(pyVer) print("Looking for the path of {}".format(pyLibName)) for process in win32process.EnumProcessModules(-1): name = win32process.GetModuleFileNameEx(-1, process) if pyLibName in name: print(name) pyLibPath = name out = parser.GetFileVersion(pyLibPath) print("pywin32 test output: {}".format(out)) out_list = out.split('.') assert int(out_list[0]) == sys.version_info[0] assert int(out_list[1]) == sys.version_info[1]