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 main(): enable_debug() pids = win32process.EnumProcesses() print "%-24s %-6s %-6s" % ("Process", "Pid", "Matched") for pid in pids: (base, size, path) = get_proc_params(pid) if not base or not size or not path: continue if path.startswith("\\??\\"): path = path[4:] elif path.startswith("\\SystemRoot"): path = path.replace("\\SystemRoot", win32api.GetWindowsDirectory()) if not os.path.isfile(path): continue dmp_file = dump_process(pid, base, size) if not dmp_file or not os.path.isfile(dmp_file): continue flag = '' percent = compare_hash(path, dmp_file) if percent <= threshold: flag = 'possible packed exe' print "%-24s %-6d %-2s%% %-24s" % (os.path.basename(path), pid, percent, flag)
def _task_list(): psapi = ctypes.windll.psapi kernel = ctypes.windll.kernel32 hModule = ctypes.c_ulong() count = ctypes.c_ulong() modname = ctypes.c_buffer(30) PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_VM_READ = 0x0010 pid_list = win32process.EnumProcesses() info_list = [] for pid in pid_list: hProcess = kernel.OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid) if hProcess: psapi.EnumProcessModules(hProcess, ctypes.byref(hModule), ctypes.sizeof(hModule), ctypes.byref(count)) psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, ctypes.sizeof(modname)) pname = ctypes.string_at(modname) procmeminfo = win32process.GetProcessMemoryInfo(hProcess) procmemusage = (procmeminfo["WorkingSetSize"] / 1024) info_list.append((pid, pname, procmemusage)) kernel.CloseHandle(hProcess) return info_list
def getProcess(): import win32process, win32api, win32con p = {} procs = win32process.EnumProcesses() for pid in procs: try: handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) except: handle = None exe = None if handle: try: executablePath = win32process.GetModuleFileNameEx(handle, 0) filename = os.path.basename(executablePath) ptimes = win32process.GetProcessTimes(handle) meminfo = win32process.GetProcessMemoryInfo(handle) pagefile = meminfo['PagefileUsage'] / (1024 * 1024) workset = meminfo['WorkingSetSize'] / (1024 * 1024) p[pid] = (ptimes['UserTime'], ptimes['KernelTime'], pagefile, workset, filename, executablePath) except: pass if handle: handle.Close() return p
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 enum_procs(proc_name=None): pids = win32process.EnumProcesses() if proc_name is not None: buf_len = 0x100 bytes = wintypes.DWORD(buf_len) _OpenProcess = ctypes.cdll.kernel32.OpenProcess _GetProcessImageFileName = ctypes.cdll.psapi.GetProcessImageFileNameA _CloseHandle = ctypes.cdll.kernel32.CloseHandle filtered_pids = () for pid in pids: try: h_proc = _OpenProcess(wintypes.DWORD(win32con.PROCESS_ALL_ACCESS), ctypes.c_int(0), wintypes.DWORD(pid)) except: print("Process [%d] couldn't be opened: %s" % (pid, traceback.format_exc())) continue try: buf = ctypes.create_string_buffer(buf_len) _GetProcessImageFileName(h_proc, ctypes.pointer(buf), ctypes.pointer(bytes)) if buf.value: name = buf.value.decode().split(os.path.sep)[-1] # print name else: _CloseHandle(h_proc) continue except: print("Error getting process name: %s" % traceback.format_exc()) _CloseHandle(h_proc) continue if name.lower() == proc_name.lower(): filtered_pids += (pid,) return filtered_pids else: return pids
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 getspwindowtext(): for PID in win32process.EnumProcesses(): if "Spotify" in psutil.Process(PID).name(): if gethwndsforpid(PID): hwnd = gethwndsforpid(PID)[0] windowText = win32gui.GetWindowText(hwnd) return windowText
def inspectHiddenProcess(): try: pidlist = list(win32process.EnumProcesses()) funclist=\ [ listProcessByPsActiveProcessHead, listProcessBySessionProcessLinks, listProcessByWorkingSetExpansionLinks, listProcessByPspcidTable, ] print 'eprocess pid ppid peb name filepath' for func in funclist: print '-' * 10, 'find hidden process by %s' % func.func_name, '-' * 10 processlist = func() #print len(processlist) pidlist2 = copy.deepcopy(pidlist) for i in processlist: if i.pid not in pidlist2: print '%x %5d %5d %x %s %s' % (i.eprocessaddr, i.pid, i.parentpid, i.peb, i.name, i.filepath) else: pidlist2.remove(i.pid) for i in pidlist2: print "pid %d can't be found by %s" % (i, func.func_name) print print 'inspect completely' except Exception, err: print traceback.format_exc()
def run_dnfbox(): while (True): strExepath = r"E:\\boxgroup\\DNFBox\\DNF盒子代码\\新版DnfBox\\trunk\\product\\bin\\win32\\Debug\\DnfBoxClient.exe" pTuple = win32process.CreateProcess( strExepath.decode('utf-8').encode('gbk'), '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) if (0 == len(pTuple)): print "Create Process Fail" print "Create Process Success" time.sleep(15) pList = win32process.EnumProcesses() if (pTuple[2] in pList): print "Terminate Process" exiCode = 0 win32process.TerminateProcess(pTuple[0], exiCode) time.sleep(2) lstDir = os.listdir(u"E:\\boxgroup\\崩溃调试\\Dump") if (0 != len(lstDir)): for item in lstDir: if (-1 != item.find("dmp")): return
def collectData(self): """Collect process list. """ self.data.datahash = {} # dict of processes keyed by pid self.data.proclist = [] # list of processes self.data.nameHash = {} # dict of processes keyed by process name procs = win32process.EnumProcesses() for pid in procs: try: han = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) except: # privileges may prevent querying the process details han = None p = proc(pid, han) if han: han.Close() self.data.proclist.append(p) self.data.datahash[p.pid] = p self.data.nameHash[p.procname] = p log.log("<proc>procList.collectData(): new proc list created", 7)
def testFirefox(): global starting start_time = 9999999999 pids = [] firefox_pids = [] over = True while 1: try: current_pids = list(win32process.EnumProcesses()) if start_time == 9999999999: diff = list(set(current_pids) - set(pids)) pids = current_pids.copy() for pid in diff: try: #print(psutil.Process(pid).name()) if "firefox" in psutil.Process(pid).name(): #print("FIREFOX FOUND") firefox_pids.append(pid) over = False p_time = psutil.Process(pid).create_time() if start_time > p_time: start_time = p_time print( "Firefox start to :", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time))) except: None elif pids != current_pids: diff_re = list(set(pids) - set(current_pids)) #liste de pids terminés diff_ad = list(set(current_pids) - set(pids)) #liste de pids ajoutés #print('PIDS DIFFERENT removed :',diff_re,' added :',diff_ad) pids = current_pids.copy() #print("FIREFOX_PIDS before remove : ",firefox_pids) for pid in diff_re: if pid in firefox_pids: firefox_pids.remove(pid) #print("FIREFOX_PIDS after remove : ",firefox_pids) for pid in diff_ad: try: if "firefox" in psutil.Process(pid).name(): firefox_pids.append(pid) except: None #print("FIREFOX_PIDS after add : ",firefox_pids) except: #print("BUUUGG") None if not firefox_pids and start_time != 9999999999 and not over: print('FIREFOX IS OVER') over = True starting = start_time start_time = 9999999999 master.deiconify() master.attributes("-topmost", True) time.sleep(0.5)
def get_processes(self): for pid in win32process.EnumProcesses(): if pid > 0: try: yield WindowsProcess(pid) except: #_logger.exception("Couldn't get process information for pid %d", pid) continue
def listprocesses(self): for process in win32process.EnumProcesses(): try: han = get_handle(process) procmeminfo = meminfo(han) procmemusage = procmeminfo["WorkingSetSize"] yield process, procmemusage except: pass
def listRunningProcessesIds(self): """ List Running Processes Ids @return: list of running processes ids """ self._log_info("Listing Running Processes ids") runningProcesses = win32process.EnumProcesses() return runningProcesses
def listRunningProcessesIds(self): """ List Running Processes Ids @return: list of running processes ids """ pylabs.q.logger.log('Listing Running Processes ids', 6) runningProcesses = win32process.EnumProcesses() return runningProcesses
def listRunningProcessesIds(self): """ List Running Processes Ids @return: list of running processes ids """ self.logger.info('Listing Running Processes ids') runningProcesses = win32process.EnumProcesses() return runningProcesses
def process_running(pid): if deluge.common.windows_check(): import win32process return pid in win32process.EnumProcesses() else: # We can just use os.kill on UNIX to test if the process is running try: os.kill(pid, 0) except OSError: return False else: return True
def get_all(self): if not self.processes: pids = win32process.EnumProcesses() try: proc_infos = win32ts.WTSEnumerateProcesses( wpc.conf.remote_server, 1, 0) except: proc_infos = [] pass for pid in pids: p = Process(pid) self.add(p) for proc_info in proc_infos: pid = proc_info[1] p = self.find_by_pid(pid) if p: # might fail to find process - race condition p.set_wts_session_id(proc_info[0]) p.set_wts_name(proc_info[2]) if proc_info[3]: # sometimes None p.set_wts_sid(Principal(proc_info[3])) TH32CS_SNAPPROCESS = 0x00000002 # See http://msdn2.microsoft.com/en-us/library/ms686701.aspx CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot Process32First = ctypes.windll.kernel32.Process32First Process32Next = ctypes.windll.kernel32.Process32Next Thread32First = ctypes.windll.kernel32.Thread32First Thread32Next = ctypes.windll.kernel32.Thread32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) pe32 = PROCESSENTRY32() pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) if Process32First(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: pass #print >> sys.stderr, "Failed getting first process." #return else: while True: p = self.find_by_pid(pe32.th32ProcessID) if p: # might fail to find process - race condition p.set_short_name(pe32.szExeFile) if Process32Next(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: break CloseHandle(hProcessSnap) return self.processes
def process_from_module(module): "Return the running process with path module" # set up the variable to pass to EnumProcesses processes = (ctypes.c_int * 2000)() bytes_returned = ctypes.c_int() modules = [] # collect all the running processes pids = win32process.EnumProcesses() for pid in pids: if pid != 0: # skip system process (0x00000000) try: modules.append((pid, process_module(pid))) except pywintypes.error as exc: pass #print(exc) except ProcessNotFoundError as exc: pass #print(exc) ''' ctypes.windll.psapi.EnumProcesses( ctypes.byref(processes), ctypes.sizeof(processes), ctypes.byref(bytes_returned)) # Get the process names for i in range(0, int(bytes_returned.value / ctypes.sizeof(ctypes.c_int))): try: if processes[i]: modules.append((processes[i], process_module(processes[i]))) except ProcessNotFoundError: pass ''' # check for a module with a matching name in reverse order # as we are most likely to want to connect to the last # run instance modules.reverse() for process, name in modules: if module.lower() in name.lower(): return process # # check if any of the running process has this module # for i in range(0, bytes_returned.value / ctypes.sizeof(ctypes.c_int)): # try: # p_module = process_module(processes[i]).lower() # if module.lower() in p_module: # return processes[i] # message = "Could not find any process with a module of '%s'" % module raise ProcessNotFoundError(message)
def _get_state(self): '''Retrieves the status of a pylabs application''' if pylabs.q.platform.isUnix(): if pylabs.q.system.fs.exists( os.path.join(os.sep, 'proc', '%d' % (self.processid))): return PMAppType.RUNNING else: return PMAppType.HALTED elif pylabs.q.platform.isWindows(): if self.processid in win32process.EnumProcesses(): return PMAppType.RUNNING else: return PMAppType.HALTED
def isrunning(pid): if hasattr(os,'kill'): try: os.kill(pid, 0) #Sending a 0 signal does nothing. return True except: return False elif iswin: import win32process try: return pid in win32process.EnumProcesses() except: return False
def process_get_modules(): """Return the list of processes as tuples (pid, exe_path)""" modules = [] # collect all the running processes pids = win32process.EnumProcesses() for pid in pids: if pid != 0 and isinstance(pid, int): # skip system process (0x00000000) try: modules.append((pid, process_module(pid), None)) except (win32gui.error, ProcessNotFoundError): continue return modules
def is_alive(pid): if sys.platform == 'win32': if pid not in win32process.EnumProcesses(): return False else: try: with open('/proc/%d/status' % pid, 'r') as f: text = f.read() match = prog.match(text) assert match.groups()[0] != 'Z' except (IOError, AttributeError, AssertionError): return False return True
def process_get_modules(): modules = [] # collect all the running processes pids = win32process.EnumProcesses() for pid in pids: if pid != 0: # skip system process (0x00000000) try: modules.append((pid, process_module(pid), None)) except win32gui.error: pass except ProcessNotFoundError: pass return modules
def getProcess(self): p = {} try: systime = self.getSystemTimes() p['total'] = systime[1] + systime[2] procs = win32process.EnumProcesses() for pid in procs: if pid ==0: continue handle = self.openProcess(pid) if handle: try: try: executablePath = win32process.GetModuleFileNameEx(handle, 0) except: executablePath = None if not executablePath: winapp = winappdbg.Process(pid) executablePath = winapp.get_filename() filename = os.path.basename(executablePath) if filename.find('TMatrix') ==0 : continue ptimes = win32process.GetProcessTimes(handle) meminfo = win32process.GetProcessMemoryInfo(handle) pagefile = meminfo['PagefileUsage']/(1024*1024) workset = meminfo['WorkingSetSize']/(1024*1024) p[str(pid)] = (ptimes['UserTime'],ptimes['KernelTime'],pagefile,workset,filename,executablePath) except Exception as myException: self.logger.error(myException) finally: self.CloseHandle(handle) except Exception as myException: self.logger.error(myException) return p
def process_id_from_path(path): lower_path = path.lower() pids = win32process.EnumProcesses() for pid in pids: if VISTA_OR_LATER: desired_access = PROCESS_QUERY_LIMITED_INFORMATION phandle = kernel32.OpenProcess(desired_access, BOOL(False), pid) if phandle is None: continue path = ctypes.create_unicode_buffer(MAX_PATH) length = DWORD(MAX_PATH) flags = DWORD(0) ret = QueryFullProcessImageName(phandle, flags, path, byref(length)) if ret != 0: found_path = path.value.lower() if found_path == lower_path: kernel32.CloseHandle(phandle) return pid else: desired_access = DWORD(PROCESS_VM_READ.value | PROCESS_QUERY_INFORMATION.value) phandle = kernel32.OpenProcess(desired_access, BOOL(False), pid) if phandle is None: continue path = ctypes.create_unicode_buffer(MAX_PATH) length = DWORD(MAX_PATH) ret = GetModuleFileNameEx(phandle, None, path, length) if ret > 0: found_path = path.value.lower() if found_path == lower_path: kernel32.CloseHandle(phandle) return pid kernel32.CloseHandle(phandle) return None
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 enum_procs(proc_name=None): pids = win32process.EnumProcesses() if proc_name is not None: buf_len = 0x100 _open_process = ctypes.cdll.kernel32.OpenProcess _open_process.argtypes = [ wintypes.DWORD, wintypes.BOOL, wintypes.DWORD ] _open_process.restype = wintypes.HANDLE _GetProcessImageFileName = ctypes.cdll.psapi.GetProcessImageFileNameA _GetProcessImageFileName.argtypes = [ wintypes.HANDLE, wintypes.LPSTR, wintypes.DWORD ] _GetProcessImageFileName.restype = wintypes.DWORD _close_handle = ctypes.cdll.kernel32.CloseHandle _close_handle.argtypes = [wintypes.HANDLE] _close_handle.restype = wintypes.BOOL filtered_pids = () for pid in pids: try: h_proc = _open_process(win32con.PROCESS_ALL_ACCESS, 0, pid) except: print("Process [%d] couldn't be opened: %s" % (pid, traceback.format_exc())) continue try: buf = ctypes.create_string_buffer(buf_len) _GetProcessImageFileName(h_proc, buf, buf_len) if buf.value: name = buf.value.decode().split(os.path.sep)[-1] # print name else: _close_handle(h_proc) continue except: print("Error getting process name: %s" % traceback.format_exc()) _close_handle(h_proc) continue if name.lower() == proc_name.lower(): filtered_pids += (pid, ) return filtered_pids else: return pids
def is_process_running_by_path(file_path: str): """Check if process running by its exe path >>> is_process_running_by_path('C:\\Windows\\explorer.exe') True :param file_path: file path """ processes = win32process.EnumProcesses() for pid in processes: try: handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid) exe = win32process.GetModuleFileNameEx(handle, 0) if exe.lower() == file_path.lower(): return True except: pass return False