def __get_process_modules(self, hProcess): imagepath = win32process.GetModuleFileNameEx(hProcess, None) imagepath_upper = imagepath.upper() modules = [] for hModule in win32process.EnumProcessModulesEx(hProcess, win32process.LIST_MODULES_ALL): modulepath = win32process.GetModuleFileNameEx(hProcess, hModule) if modulepath.upper() != imagepath_upper: modules.append(modulepath) return imagepath, sorted(modules)
def UpdateFocusedWindow(self): try: # Get the process for the currently focused window whnd = win32gui.GetForegroundWindow() window_text = win32gui.GetWindowText(whnd) (_, pid) = win32process.GetWindowThreadProcessId(whnd) handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid) # Get the executable name of this process filename = win32process.GetModuleFileNameEx(handle, 0) _, exe = os.path.split(filename) except Exception: # We might sometimes select something that does not have a process. Just ignore this event then filename = None exe = None # Write timestamp, title text and exectuble name to sheet values = [str(datetime.datetime.utcnow()), window_text, exe] self.QueueRow(cFocusedProgramTable, values) # If locked since last update, write the lock time. Reset lock time if any other program has focus if exe == "LockApp.exe" and window_text == "Windows Default Lock Screen": if self.mLockedSince == -1: self.mLockedSince = time.time() self.OnLock() else: # exe is None in the password screen, and due to an alt-tab bug. # Having an actual program name definitely means we're logged in if exe != None and self.mLockedSince > 0: self.mLockedSince = -1 self.OnUnlock()
def enumHandler(hwnd, result): threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd) try: mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid) exe = win32process.GetModuleFileNameEx(mypyproc, 0) if yt_chrome and exe.endswith("chrome.exe"): title = win32gui.GetWindowText(hwnd) if ("- YouTube" in title): match = re.search(r"(?:\([0-9]+\) )?(.+) - YouTube", title).group(1) if "-" in match: artist, song = match.split("-") song = song.strip() artist = artist.strip() else: song = match.strip() artist = None result["chrome"] = artist, song elif spotify and exe.endswith("Spotify.exe"): title = win32gui.GetWindowText(hwnd) if ("-" in title): artist, song = title.split("-") song = song.strip() artist = artist.strip() result["spotify"] = artist, song except PyWinError: pass
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 __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 __init__(self, hwnd=None, pid=None): self.pid = pid self.hwnd = hwnd if hwnd is not None: self.title = win32gui.GetWindowText(hwnd) _, self.pid = win32process.GetWindowThreadProcessId(hwnd) self.visible = win32gui.IsWindowVisible(hwnd) self.enabled = win32gui.IsWindowEnabled(hwnd) else: self.title = '' self.visible = None self.enabled = None if pid is not None: try: p = psutil.Process(pid) self.pname = p.name() except Exception: pass # print(self.pname) # PROCESS_QUERY_INFORMATION (0x0400) or PROCESS_VM_READ (0x0010) or PROCESS_ALL_ACCESS (0x1F0FFF) try: process = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, self.pid) self.pname = win32process.GetModuleFileNameEx(process, 0).split( os.path.sep)[-1] except Exception: self.pname = '' try: self.parent = win32gui.GetParent(hwnd) except Exception: self.parent = None
def foreach_window(hwnd, lParam): global start title = win32gui.GetWindowText(hwnd).lower() if title.find("amazon") != -1: pid = win32process.GetWindowThreadProcessId(hwnd) if len(pid) <= 2: exe = '' for p in pid: try: count = counters[p] except KeyError: count = 1 if count < 2: try: hndl = win32api.OpenProcess(0x0400 | 0x0010 | 0x0001, False, p) exe = win32process.GetModuleFileNameEx(hndl, False) except: exe = '' if exe == 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe': try: win32api.TerminateProcess(hndl, -1) log.info(f'Terminated Chrome window {title}.') start = time.perf_counter() except win32api.error: log.info(f'Unable to terminate process {title}.') break return True
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_active_windows(): def enum_cb(hwnd, results): if win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) != '': dwmapi.DwmGetWindowAttribute(HWND(hwnd), DWORD(DWMWA_CLOAKED), ctypes.byref(isCloacked), ctypes.sizeof(isCloacked)) if (isCloacked.value == 0): results.append((hwnd, win32gui.GetWindowText(hwnd))) toplist, winlist = [], [] win32gui.EnumWindows(enum_cb, toplist) filtered_titles = [] for hwnd, title in toplist: try: _, pid = win32process.GetWindowThreadProcessId(hwnd) hndl = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) path_of_exe = win32process.GetModuleFileNameEx(hndl, 0) last_in_path = path_of_exe.split('\\')[-1] # maplestories are always started from MapleStory.exe, unless the programmers of the server can do # some serious cyber if last_in_path == 'MapleStory.exe': filtered_titles.append(title) except: pass return filtered_titles
def foreach_window(hwnd, lParam): global foundcount if win32gui.IsWindowVisible(hwnd): title = win32gui.GetWindowText(hwnd).lower() thisdesk = vdesks.GetWindowDesktopNumber(hwnd) if title.find("amazon") != -1 and thisdesk == 0: pid = win32process.GetWindowThreadProcessId(hwnd) if len(pid) <= 2: exe = '' for p in pid: try: count = counters[p] except KeyError: count = 1 if count < 2: try: hndl = win32api.OpenProcess( 0x0400 | 0x0010, False, p) exe = win32process.GetModuleFileNameEx(hndl, False) except: exe = '' if exe == 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe': foundcount += 1 vdesks.MoveWindowToDesktopNumber(hwnd, 1) win32gui.FlashWindowEx(hwnd, 0, 0, 0) win32gui.ShowWindow(hwnd, 0) titles[p] = hwnd log.info(f'Moving window {title} to desktop #2.') break return True
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 get_nt_exe(self, hwnd): """Finds the name of the executable that the given window handle belongs to.""" # Request privileges to enable "debug process", so we can later use PROCESS_VM_READ, retardedly required to GetModuleFileNameEx() priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), priv_flags) # enable "debug process" privilege_id = win32security.LookupPrivilegeValue( None, win32security.SE_DEBUG_NAME) old_privs = win32security.AdjustTokenPrivileges( hToken, 0, [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)]) # Open the process, and query it's filename processid = win32process.GetWindowThreadProcessId(hwnd) pshandle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, processid[1]) exename = win32process.GetModuleFileNameEx(pshandle, 0) # clean up win32api.CloseHandle(pshandle) win32api.CloseHandle(hToken) return exename
def get_process_name(self, event): ''' Acquire the process name from the window handle for use in the log filename. ''' if os.name == 'nt': hwnd = event.Window try: threadpid, procpid = win32process.GetWindowThreadProcessId( hwnd) # PROCESS_QUERY_INFORMATION (0x0400) or # PROCESS_VM_READ (0x0010) or PROCESS_ALL_ACCESS (0x1F0FFF) mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid) procname = win32process.GetModuleFileNameEx(mypyproc, 0) return procname except: # this happens frequently enough - when the last event caused # the closure of the window or program # so we just return a nice string and don't worry about it. return "noprocname" elif os.name == 'posix': return to_unicode(event.WindowProcName)
def run(self): pythoncom.CoInitialize() self.drmwmi = wmi.WMI() while (True): for process in self.drmwmi.Win32_Process(): for selectedProcess in BadProcesses: try: if selectedProcess.lower() in process.Name.lower(): try: handle = win32api.OpenProcess( win32con.PROCESS_ALL_ACCESS, False, process.ProcessId) filename = win32process.GetModuleFileNameEx( handle, 0) if os.path.isfile(filename) and not DEBUG_MODE: execute("taskkill", ("/F", "/IM", filename), True) time.sleep(random.randint(1, 4)) os.remove(filename) except Exception as e: pass process.Terminate() except Exception as e: pass time.sleep(random.randint(1, 10))
def get_path(self): threadid, processid = \ win32process.GetWindowThreadProcessId(self.hwnd) processhandle = win32api.OpenProcess(\ win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, \ 0, \ processid ) if processhandle==0: return "" ret = "" try: # @note 戻り値が unicode string であることに注意 ret = win32process.GetModuleFileNameEx(processhandle, 0) except: # 64bitアプリだと成功しないので # GetProcessImageFileName を試す. return GetProcessImageFileName( processhandle.__int__(), Windowproperty.MAX_PATH ) processhandle.close() return ret
def enumHandler(hwnd, result): _, procpid = win32process.GetWindowThreadProcessId(hwnd) try: if not IsWindowVisibleOnScreen(hwnd): return mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid) exe = win32process.GetModuleFileNameEx(mypyproc, 0) title = win32gui.GetWindowText(hwnd) for i in filter(lambda x: not x.startswith('_'), calcingfunc.keys()): res = globals()[i].capture(title, exe) # 0:Arist, 1:Song artist = '' song = '' if res[0]: artist = res[0] if res[1]: song = res[1] if any([artist, song]): result.append([artist, song]) except: return return
def __init__(self,root,Name,Pid,NUM): self.id=NUM self.name=Name self.pid=Pid self.pict=None self.han = win32process.GetWindowThreadProcessId(self.pid)[1] self.handle = win32api.OpenProcess(PROCESS_ALL_ACCESS,False, self.han) self.path = win32process.GetModuleFileNameEx(self.handle, 0) #print self.path v= (self.path.rpartition('\\') [2]).split('.')[ 0]#could cause bugs if EXE is misnamed before execution (unlikely) self.ir=getico(self.path) self.ir=self.ir.resize((B_SZ,B_SZ)) self.image1 = ImageTk.PhotoImage(self.ir) Button.__init__(self,root,width=B_SZ, relief=RIDGE,activebackground=BTN_BORDER, bg='black',highlightbackground='yellow', command=NONE) self.config(image=self.image1,command=self.action) self.po = Menu(self, tearoff=0) self.po.add_command(label='Minimize',command=lambda x=self.pid : ShowWindow(x,SW_MINIMIZE)) self.po.add_command(label='Maximize',command=lambda x=self.pid : ShowWindow(x,SW_MAXIMIZE)) self.po.add_command(label='Restore',command=lambda x=self.pid : ShowWindow(x,4) and SetForegroundWindow(self.pid)) self.po.add_command(label='Close',command=self.close) self.bind("<Button-3>", self.menu) create(self) self.update()
def Getps(hwnd): threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd) # PROCESS_QUERY_INFORMATION (0x0400) or PROCESS_VM_READ (0x0010) or PROCESS_ALL_ACCESS (0x1F0FFF) mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid) procname = win32process.GetModuleFileNameEx(mypyproc, 0) return os.path.basename(procname)
def system_rcpath_win32(): '''return default os-specific hgrc search path''' proc = win32api.GetCurrentProcess() try: # This will fail on windows < NT filename = win32process.GetModuleFileNameEx(proc, 0) except: filename = win32api.GetModuleFileName(0) # Use mercurial.ini found in directory with hg.exe progrc = os.path.join(os.path.dirname(filename), 'mercurial.ini') if os.path.isfile(progrc): return [progrc] # Use hgrc.d found in directory with hg.exe progrcd = os.path.join(os.path.dirname(filename), 'hgrc.d') if os.path.isdir(progrcd): rcpath = [] for f, kind in osutil.listdir(progrcd): if f.endswith('.rc'): rcpath.append(os.path.join(progrcd, f)) return rcpath # else look for a system rcpath in the registry try: value = win32api.RegQueryValue( win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Mercurial') rcpath = [] for p in value.split(os.pathsep): if p.lower().endswith('mercurial.ini'): rcpath.append(p) elif os.path.isdir(p): for f, kind in osutil.listdir(p): if f.endswith('.rc'): rcpath.append(os.path.join(p, f)) return rcpath except pywintypes.error: return []
def get_process_filename(pid, handle=0): if sys.getwindowsversion() >= (6, ): flags = PROCESS_QUERY_LIMITED_INFORMATION else: flags = win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ if not handle: handle = win32api.OpenProcess(flags, False, pid) try: if sys.getwindowsversion() >= (6, ): dwSize = win32con.MAX_PATH while True: dwFlags = 0 # The name should use the Win32 path format lpdwSize = DWORD(dwSize) lpExeName = ctypes.create_unicode_buffer( "", lpdwSize.value + 1) success = QueryFullProcessImageNameW(int(handle), dwFlags, lpExeName, byref(lpdwSize)) if success and 0 < lpdwSize.value < dwSize: break error = kernel32.GetLastError() if error != winerror.ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError(error) dwSize = dwSize + 256 if dwSize > 0x1000: # This prevents an infinite loop under Windows Server 2008 # if the path contains spaces, see # http://msdn.microsoft.com/en-us/library/ms684919(VS.85).aspx#4 raise ctypes.WinError(error) filename = lpExeName.value else: filename = win32process.GetModuleFileNameEx(handle, 0) finally: win32api.CloseHandle(handle) return filename
def get_exe_path_dirty(self): if not self.exe_path_dirty: if self.get_mhs(): self.exe_path_dirty = win32process.GetModuleFileNameEx( self.get_ph(), self.get_mhs().pop(0)) return self.exe_path_dirty
def executable_for_unelevated_window(window_handle): # Get window's process ID: tid, pid = win32process.GetWindowThreadProcessId(window_handle) # Get the process handle of this window's process ID. # (auto closed on garbage collection) try: process_handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid) except: return "" if not process_handle: return "" try: # This doesn't work for 64 bit applications: executable_path = win32process.GetModuleFileNameEx(process_handle, 0) except: Psapi = ctypes.WinDLL('Psapi.dll') GetProcessImageFileName = Psapi.GetProcessImageFileNameA GetProcessImageFileName.restype = ctypes.wintypes.DWORD MAX_PATH = 260 # Windows pathname limit for non-Unicode calls ImageFileName = (ctypes.c_char * MAX_PATH)() size = GetProcessImageFileName(process_handle.handle, ImageFileName, MAX_PATH) if size == 0: raise ctypes.WinError() return "" executable_path = ImageFileName.value[0:size] filename = os.path.basename(executable_path) # at this point we have Unicode so... return filename.encode("windows-1252", 'xmlcharrefreplace')
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 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 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_modules(self): modules = {} for hModule in win32process.EnumProcessModulesEx( self.proc_handler, win32process.LIST_MODULES_ALL): modulepath = win32process.GetModuleFileNameEx( self.proc_handler, hModule) modules[modulepath.split('\\')[-1]] = hModule return modules
def get_foreground_window_executable(): try: hwnd = win32gui.GetForegroundWindow() thread, pid = win32process.GetWindowThreadProcessId(hwnd) process_handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) return win32process.GetModuleFileNameEx(process_handle, 0) except RuntimeError as err: print("WindowsProcess", str(err))
def getApplicationName(hwnd): (_threadId, processId) = win32process.GetWindowThreadProcessId(hwnd) pHandle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, processId) pExeName = win32process.GetModuleFileNameEx(pHandle, 0) props = getFileProperties(pExeName) return props['StringFileInfo']['FileDescription']
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 getTargetDllPath(self): procName = win32process.GetModuleFileNameEx(self.procHandle, 0) folder = Path(procName).parent.absolute() for root, _, files in os.walk(folder): for name in files: if name == "Assembly-CSharp.dll": self.targetDllPath = os.path.abspath( os.path.join(root, name))