Python win32api.OpenProcess() Examples
The following are 24
code examples of win32api.OpenProcess().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
win32api
, or try the search function
.
Example #1
Source File: windows-privesc-check.py From WHP with Do What The F*ck You Want To Public License | 6 votes |
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))
Example #2
Source File: win32-identd.py From code with MIT License | 6 votes |
def get_pid_owner(self, fd, pid): try: proc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) token = win32security.OpenProcessToken(proc, win32con.TOKEN_QUERY) user_sid, user_attr = win32security.GetTokenInformation(token, win32security.TokenUser) user = win32security.LookupAccountSid(None, user_sid) return user_sid, user[0], user[1] except win32api.error as e: self.logEx("error", "%s failed" % funcname, ("exception", e), ("function", e.funcname), ("error", "[%(winerror)d] %(strerror)s" % e), None, ("process", pid),) raise
Example #3
Source File: windowsprivcheck.py From LHF with GNU General Public License v3.0 | 6 votes |
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))
Example #4
Source File: service_wrapper.py From resilient-python-api with MIT License | 6 votes |
def SvcDoRun(self): import servicemanager servicemanager.LogInfoMsg(self._svc_name_ + " Start Requested") try: hJob = win32job.CreateJobObject(None, "") extended_info = win32job.QueryInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation) extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE win32job.SetInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation, extended_info) command = "resilient-circuits.exe run " + self._resilient_args_ command_args = shlex.split(command) self.process_handle = subprocess.Popen(command_args) # Convert process id to process handle: perms = win32con.PROCESS_TERMINATE | win32con.PROCESS_SET_QUOTA hProcess = win32api.OpenProcess(perms, False, self.process_handle.pid) win32job.AssignProcessToJobObject(hJob, hProcess) except: servicemanager.LogErrorMsg(self._svc_name_ + " failed to launch resilient-circuits.exe") raise servicemanager.LogInfoMsg(self._svc_name_ + " Started") while self.isAlive: if self.process_handle.poll() != None: self.SvcStop() win32api.SleepEx(10000, True)
Example #5
Source File: process.py From peach with Mozilla Public License 2.0 | 6 votes |
def closeApp(self, hProcess, title): """ Close Application by window title """ try: win32gui.EnumWindows(FileWriterLauncherGui.enumCallback, title) if hProcess is not None: win32event.WaitForSingleObject(hProcess, 5 * 1000) win32api.CloseHandle(hProcess) for pid in self.genChildProcesses(proc): try: handle = win32api.OpenProcess(1, False, pid) win32process.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except: pass except: pass
Example #6
Source File: process.py From peach with Mozilla Public License 2.0 | 6 votes |
def closeApp(self, hProcess, title): """ Close Application by window title """ try: win32gui.EnumWindows(FileWriterLauncherGui.enumCallback, title) if proc is not None: win32event.WaitForSingleObject(hProcess, 5 * 1000) win32api.CloseHandle(hProcess) for pid in self.genChildProcesses(proc): try: handle = win32api.OpenProcess(1, False, pid) win32process.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except: pass except: pass
Example #7
Source File: win_vmmap.py From IDAngr with BSD 2-Clause "Simplified" License | 5 votes |
def vmmap(pid, is_64=True): base = 0 if is_64: mbi = MEMORY_BASIC_INFORMATION_64() addr_type = wintypes.LARGE_INTEGER else: mbi = MEMORY_BASIC_INFORMATION_32() addr_type = wintypes.DWORD proc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, 0, pid) maps = [] while windll.kernel32.VirtualQueryEx(proc.handle, addr_type(base), ctypes.byref(mbi), ctypes.sizeof(mbi)) > 0: mapperm = 0 if mbi.Protect & win32con.PAGE_EXECUTE: mapperm = SEG_PROT_X elif mbi.Protect & win32con.PAGE_EXECUTE_READ: mapperm = SEG_PROT_X | SEG_PROT_R elif mbi.Protect & win32con.PAGE_EXECUTE_READWRITE: mapperm = SEG_PROT_X | SEG_PROT_R | SEG_PROT_W elif mbi.Protect & win32con.PAGE_EXECUTE_WRITECOPY: mapperm = SEG_PROT_X | SEG_PROT_R elif mbi.Protect & win32con.PAGE_NOACCESS: mapperm = 0 elif mbi.Protect & win32con.PAGE_READONLY: mapperm = SEG_PROT_R elif mbi.Protect & win32con.PAGE_READWRITE: mapperm = SEG_PROT_R | SEG_PROT_W elif mbi.Protect & win32con.PAGE_WRITECOPY: mapperm = SEG_PROT_R #print hex(mbi.BaseAddress) +"\t"+ hex(mbi.BaseAddress + mbi.RegionSize) +"\t"+ hex(mapperm) maps.append((mbi.BaseAddress, mbi.BaseAddress + mbi.RegionSize, mapperm, "")) base += mbi.RegionSize win32api.CloseHandle(proc) return maps
Example #8
Source File: Utils.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def KillProcess(pid = None, processName = None, hwnd = None, signal = 0, restart = False): if pid: pass elif processName: pids = GetPids(processName = processName) if pids: pid = pids[0] else: return False elif hwnd: hwnd = GetBestHwnd(hwnd) pids = GetPids(hwnd = hwnd) if pids: pid = pids[0] else: return False else: return False fullPath = GetProcessNameEx(pid = pid, fullPath = True) try: proc = OpenProcess(1, 0, pid) TerminateProcess(proc, signal) if restart: eg.plugins.System.Execute(fullPath) return True except: return False
Example #9
Source File: login.py From code with MIT License | 5 votes |
def Popen(*args, **kwargs): kwargs["creationflags"] = kwargs.get("creationflags", 0) #kwargs["creationflags"] |= BELOW_NORMAL_PRIORITY_CLASS proc = subprocess.Popen(*args, **kwargs) hproc = win32api.OpenProcess(PROCESS_SET_INFORMATION, False, proc.pid) #time.sleep(10) #win32process.SetPriorityClass(hproc, NORMAL_PRIORITY_CLASS)
Example #10
Source File: pykill.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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
Example #11
Source File: tools.py From darkc0de-old-stuff with GNU General Public License v3.0 | 5 votes |
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)
Example #12
Source File: logwriter.py From darkc0de-old-stuff with GNU General Public License v3.0 | 5 votes |
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
Example #13
Source File: lockfile.py From python-for-android with Apache License 2.0 | 5 votes |
def kill(pid, signal): try: OpenProcess(0, 0, pid) except pywintypes.error, e: if e.args[0] == ERROR_ACCESS_DENIED: return elif e.args[0] == ERROR_INVALID_PARAMETER: raise OSError(errno.ESRCH, None) raise
Example #14
Source File: debugger.py From peach with Mozilla Public License 2.0 | 5 votes |
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
Example #15
Source File: lockfile.py From learn_python3_spider with MIT License | 5 votes |
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
Example #16
Source File: guiminer.py From poclbm with GNU General Public License v3.0 | 5 votes |
def set_process_affinity(pid, mask): """Set the affinity for process to mask.""" flags = win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_SET_INFORMATION handle = win32api.OpenProcess(flags, 0, pid) win32process.SetProcessAffinityMask(handle, mask)
Example #17
Source File: guiminer.py From poclbm with GNU General Public License v3.0 | 5 votes |
def get_process_affinity(pid): """Return the affinity mask for the specified process.""" flags = win32con.PROCESS_QUERY_INFORMATION handle = win32api.OpenProcess(flags, 0, pid) return win32process.GetProcessAffinityMask(handle)[0]
Example #18
Source File: WindowsServer.py From pycopia with Apache License 2.0 | 5 votes |
def kill(self): handle = win32api.OpenProcess( win32con.PROCESS_VM_READ | win32con.PROCESS_TERMINATE, pywintypes.FALSE, self.childpid) win32process.TerminateProcess(handle, 3)
Example #19
Source File: WindowsServer.py From pycopia with Apache License 2.0 | 5 votes |
def _scan_for_self(self): win32api.Sleep(2000) # sleep to give time for process to be seen in system table. basename = self.cmdline.split()[0] pids = win32process.EnumProcesses() if not pids: UserLog.warn("WindowsProcess", "no pids", pids) for pid in pids: try: handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, pywintypes.FALSE, pid) except pywintypes.error, err: UserLog.warn("WindowsProcess", str(err)) continue try: modlist = win32process.EnumProcessModules(handle) except pywintypes.error,err: UserLog.warn("WindowsProcess",str(err)) continue
Example #20
Source File: lockfile.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
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
Example #21
Source File: windows-privesc-check.py From WHP with Do What The F*ck You Want To Public License | 5 votes |
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
Example #22
Source File: killProcName.py From ironpython2 with Apache License 2.0 | 5 votes |
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
Example #23
Source File: process.py From peach with Mozilla Public License 2.0 | 4 votes |
def callWindows(self): """ Launch program to consume file """ # Launch via spawn realArgs = ["cmd.exe", "/c", self.command] for a in self.args: realArgs.append(a) phandle = os.spawnv(os.P_NOWAIT, os.path.join(os.getenv('SystemRoot'), 'system32', 'cmd.exe'), realArgs) # Give it some time before we KILL! for i in range(int(self.waitTime / 0.25)): if win32process.GetExitCodeProcess(phandle) != win32con.STILL_ACTIVE: # Process exited already break time.sleep(0.25) try: pid = ctypes.windll.kernel32.GetProcessId(ctypes.c_ulong(phandle)) if pid > 0: for cid in self.FindChildrenOf(pid): chandle = win32api.OpenProcess(1, 0, cid) win32process.TerminateProcess(chandle, 0) try: win32api.CloseHandle(chandle) except: pass win32process.TerminateProcess(phandle, 0) try: win32api.CloseHandle(phandle) except: pass except: pass
Example #24
Source File: windowsprivcheck.py From LHF with GNU General Public License v3.0 | 4 votes |
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