def prepare_uninstall(): # Kill CPS & RM lst_killprocess = [ "Motorola.CommonCPS.RadioManagement.Shell.exe", "mototrbocps.exe" ] tasklistrl = os.popen("tasklist").readlines() for task in tasklistrl: for process in lst_killprocess: if len(process) < 29: if process == task[0:len(process)]: print(process) pid = int(task[29:34]) print(pid) try: handle = win32api.OpenProcess(1, False, pid) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) print("Successfully killed process %s on pid %d." % (task[0:len(process)], pid)) except: pass else: if process[0:25] == task[0:25]: print(process) pid = int(task[29:34]) print(pid) try: handle = win32api.OpenProcess(1, False, pid) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) print("Successfully killed process %s on pid %d." % (task[0:len(process)], pid)) except: pass
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
def KillPID(self): """ Kill VNC instance, called by the Stop Button or Application ends. @author: Derek Buranen @author: Aaron Gerber """ if self.returnPID != 0: print _("Processes.KillPID(%s)") % str(self.returnPID) if sys.platform == 'win32': import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, self.returnPID) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) elif re.match('(?:open|free|net)bsd|linux', sys.platform): # New processes are created when you made connections. So if you kill self.returnPID, # you're just killing the dispatch process, not the one actually doing business... os.spawnlp(os.P_NOWAIT, 'pkill', 'pkill', '-f', 'vncviewer') os.spawnlp(os.P_NOWAIT, 'pkill', 'pkill', '-f', 'x11vnc') else: os.kill(self.returnPID, signal.SIGKILL) try: os.waitpid(self.returnPID, 0) except: pass self.returnPID = 0 return
def run(self): self._visualizer.start() if self._config['TLM']: self._tlm = subprocess.Popen(self._exe, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) while not self._killed: try: line = self._tlm.stdout.readline() if line: print line, self._visualizer.encounterLine(line) else: break except IOError: if not self._killed: print "Exceptions in run" else: for i in range(10, int(self._config['NT']) + 1, 10): self._visualizer.encounterLine(str(i)) if not self._killed: self._visualizer.join() else: if sys.platform.find("win") == 0: try: import win32api h = win32api.OpenProcess(1, True, self._tlm.pid) win32api.TerminateProcess(h, 1) except: pass else: os.kill(self._tlm.pid, signal.SIGINT) self._tlm.wait()
def kill(self): # Recipes #http://me.in-berlin.de/doc/python/faq/windows.html#how-do-i-emulate-os-kill-in-windows #http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462 """kill function for Win32""" win32api.TerminateProcess(int(self._handle), 0) # returns None
def cmd_kill(ensoapi, process_name): """ Kills the processes with the given name """ pids = win32pdhutil.FindPerformanceAttributesByName(process_name) for p in pids: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle)
def Kill_(self): """Try and kill the application Dialogs may pop up asking to save data - but the application will be killed anyway - you will not be able to click the buttons. this should only be used when it is OK to kill the process like you would in task manager. """ windows = self.windows_(visible_only=True) for win in windows: win.SendMessageTimeout( win32defines.WM_QUERYENDSESSION, timeout=.5, timeoutflags=(win32defines.SMTO_ABORTIFHUNG)) # | #win32defines.SMTO_NOTIMEOUTIFNOTHUNG)) # | #win32defines.SMTO_BLOCK) try: win.Close() except TimeoutError: pass # window has let us know that it doesn't want to die - so we abort # this means that the app is not hung - but knows it doesn't want # to close yet - e.g. it is asking the user if they want to save #print "supposedly closed all windows!" # so we have either closed the windows - or the app is hung # get a handle we can wait on try: process_wait_handle = win32api.OpenProcess( win32defines.SYNCHRONIZE | win32defines.PROCESS_TERMINATE, 0, self.process) except win32gui.error: return True # already killed killed = True if process_wait_handle: # wait for the window to close win32event.WaitForSingleObject( process_wait_handle, int(Timings.after_windowclose_timeout * 1000)) try: win32api.TerminateProcess(process_wait_handle, 0) except win32gui.error: pass #print('Warning: ' + str(exc)) #win32functions.TerminateProcess(process_wait_handle, 0) #else: # killed = False win32api.CloseHandle(process_wait_handle) return killed
def kill(pid, sig=signal.SIGTERM): # http://www.python.org/doc/faq/windows/ import win32api if sig != signal.SIGTERM: raise OSError("Sending any signal except SIGTERM is not supported on Windows.") handle = win32api.OpenProcess(1, 0, pid) return (0 != win32api.TerminateProcess(handle, 0))
def TerminateProcess(process_info): try: win32api.TerminateProcess(int(process_info._handle), -1) print process_info.pid, "killed, maybe not a good way." except pywintypes.error: logger = logging.getLogger(__name__) logger.info("killing failed, app may terminated by itself: "+str(process_info.pid))
def killAllProcName(procname): """ Terminates _all_ processes with procname. Administrator can end processes owned by the system account. """ try: win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname) except: pass pids = win32pdhutil.FindPerformanceAttributesByName(procname) try: pids.remove(win32api.GetCurrentProcessId()) except ValueError: pass success = 1 if len(pids) > 0: priv = win32security.LookupPrivilegeValue(None, win32con.SE_DEBUG_NAME) newpriv = [(priv, win32con.SE_PRIVILEGE_ENABLED)] flags = ntsecuritycon.TOKEN_ADJUST_PRIVILEGES | ntsecuritycon.TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) win32security.AdjustTokenPrivileges(htoken, False, newpriv) result = [] for p in pids: try: handle = win32api.OpenProcess(True, win32con.PROCESS_TERMINATE, p) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except win32api.error: success = 0 return success
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 kill(pid): import win32api # constants pulled from win32con to save memory PROCESS_TERMINATE = 1 # from win32con handle = win32api.OpenProcess(PROCESS_TERMINATE, 0,pid) win32api.TerminateProcess(handle,0) win32api.CloseHandle(handle)
def kill_pid(pid): import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle)
def kill_process(pid, exit_code=None): """ Kill a specific process. :param pid: The process ID of the process to be terminated. :param exit_code: The exit code that the terminated process should return. (Default is DEFAULT_TERMINATION_EXIT_CODE.) :return: Whether the process was successfully terminated. """ if exit_code is None: exit_code = DEFAULT_TERMINATION_EXIT_CODE try: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid) except pywintypes.error: return False # "The parameter is incorrect." if not handle: return False try: win32api.TerminateProcess(handle, exit_code) return True except pywintypes.error: return False # "Access is denied." finally: win32api.CloseHandle(handle)
def SvcDoRun(self): logging.info( 'Starting {name} service ...'.format(name=self._svc_name_)) os.chdir(INSTDIR) # so that proj beat can be found logging.info('cwd: ' + os.getcwd()) self.ReportServiceStatus(win32service.SERVICE_RUNNING) command = '"{celery_path}" -A {proj_dir} beat -f "{log_path}" -l info --max-interval=10'.format( celery_path=os.path.join(PYTHONSCRIPTPATH, 'celery.exe'), proj_dir=PROJECTDIR, log_path=os.path.join(INSTDIR, 'celery_beat.log')) logging.info('command: ' + command) args = shlex.split(command) proc = subprocess.Popen(args) logging.info('pid: {pid}'.format(pid=proc.pid)) self.timeout = 3000 while True: rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) if rc == win32event.WAIT_OBJECT_0: # stop signal encountered # terminate process 'proc' PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, proc.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) break
def kill_process(process, log=None): """ To kill a process launched by Popen_timer, if timeout is reached (POPEN_TIMEOUT). This function is called by a threading.Timer object. The process terminates and returns EXIT_KILL_PTIMER as errorlevel code. process: process object, as created by Popen. log: optional logging module to log eventual debug and error messages. (may be the standard logging module, or any compatible object with exception and debug methods) """ # All the process output is logged at debug level, BUT only if stdout # and stderr were defined as "PIPE" when calling Popen_timer: if process.stdout and log: log.debug("Process display:") log.debug(process.stdout.read()) if process.stderr and log: log.debug(process.stderr.read()) try: if sys.platform == 'win32': reqdAccess = win32con.PROCESS_TERMINATE # or PROCESS_ALL_ACCESS ? #TODO: see MSDN and win32con.py, change reqdAccess if error. handle = win32api.OpenProcess(reqdAccess, True, process.pid) win32api.TerminateProcess(handle, EXIT_KILL_PTIMER) else: #TODO: a tester pour les autres OS os.kill(processus.pid, signal.SIGKILL) if log: log.debug("Process PID=%d killed." % process.pid) except: if log: # log or display the whole exception: log.exception("Unable to kill process PID=%d." % process.pid) # raise exception raise
def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: # block waiting for the process to finish or the interrupt to happen handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len( handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: # the process has ended naturally return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects"
def KillNameserver1(self, event): #Shutdown any Nameservers running on this computer. if windows: PROCESS_TERMINATE = 1 for pid in self.pids: try: handle = win32api.OpenProcess(PROCESS_TERMINATE, False, pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except: pass elif unix: killArray = ["kill"] for pid in self.pids: killArray[len(killArray):] = [str(pid)] Popen(killArray) ##If cluster mode, delete the cluster script file at this point if self.settings["Cluster"]: if not self.settings["Debug"]: if os.path.exists(CLUSTER_FILE_PATH): os.remove(CLUSTER_FILE_PATH) else: print "%s not found" % CLUSTER_FILE_PATH self.OnClose()
def do_terminate(self): assert self.hProcess is not None assert self.hThread is not None start = default_timer() logging.debug("ATTEMPT at termination") graceful = True if graceful: logging.debug("### send Ctrl+C") # avoid terminating our process win32api.SetConsoleCtrlHandler(None, True) win32api.GenerateConsoleCtrlEvent(win32console.CTRL_C_EVENT, self.pid) else: win32api.TerminateProcess(self.hProcess, 15) self.post_terminate() logging.debug("POST terminate DONE") # If the HandlerRoutine parameter is NULL, a # TRUE value causes the calling process to ignore CTRL+C input, and a # FALSE value restores normal processing of CTRL+C input. This attribute of ignoring or processing CTRL+C is inherited by child processes. # # HAS TO BE called AFTER process has been terminated win32api.SetConsoleCtrlHandler(None, False) diff = default_timer() - start logger.debug("Termination took: %.4f" % diff) logging.debug("TERMINATE OVER")
def close(self): """ close this browser """ result = None if self.browser is not None: try: # windows kill process (either way works) import win32api if False: # use the api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, self.browser.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) else: # use the command line cmd = 'taskkill /PID ' + str(self.browser.pid) + ' /T' result = Popen(cmd, stdout=PIPE).communicate()[0] except ImportError: # posix kill process os.kill(self.browser.pid, signal.SIGTERM) waitcycles = 10 while self.browser.poll() < 0: time.sleep(0.1) waitcycles = waitcycles - 1 if waitcycles <= 0: os.kill(self.browser.pid, -9) self.browser.poll() break self.browser = None return result
def killProcess(self, pid): try: hProcess = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, int(pid)) win32api.TerminateProcess(hProcess, 0) except: print traceback.print_exc()
def _kill(pid, sig): try: proch = win32api.OpenProcess(PROCESS_TERMINATE, 0, pid) win32api.TerminateProcess(proch, 1) win32api.CloseHandle(proch) except pywintypes.error, e: pass
def kill_process_by_name(name): """Find and kill all processes containing a certain name""" pids = get_pids(name) if sys.platform == 'win32': import win32api, win32con for p in pids: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) #get process handle win32api.TerminateProcess(handle, 0) #kill by handle win32api.CloseHandle(handle) #close api else: for pid in pids: try: os.kill(pid, signal.SIGTERM) except OSError: pass sleep(.5) if len(get_pids(name)) is not 0: try: os.kill(pid, signal.SIGKILL) except OSError: pass sleep(.5) if len(get_pids(name)) is not 0: logger.error('Could not kill process')
def abort_now(): """Abort the current process without doing any exception teardown""" sys.stdout.flush() if win32api: win32api.TerminateProcess(win32api.GetCurrentProcess(), 3) else: os.kill(0, 9)
def killPID(self, pid): if os.name == 'nt' or os.name == 'dos': try: import win32api win32api.TerminateProcess(pid, 0) except BaseException, ex: raise ProcError("WIN32 API not available!" + str(ex))
def close_excel_by_force(excel): """ close_excel_by_force() -> None --``excel`` must be an Excel Application instance Method closes all Excel instances by brute force. No other way to close out all lingering threads. Source: http://stackoverflow.com/questions/10221150/cant-close-excel-completely-using-win32com-on-python """ # Get the window's process id's hwnd = excel.Hwnd t, p = win32process.GetWindowThreadProcessId(hwnd) # Ask window nicely to close win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) # If the application didn't close, force close try: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) if handle: win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) except: pass
def kill_pid(self, pid): """ Kills the given PID, if possible :param pid: PID of the process to kill :raise ValueError: Invalid PID :raise OSError: Unauthorized operation """ if pid is None or not self.is_process_running(pid): raise ValueError("Invalid PID: {0:d}".format(pid)) handle = None try: handle = win32api.OpenProcess(PROCESS_TERMINATE, False, pid) win32api.TerminateProcess(handle, -1) except pywintypes.error as ex: # PID not in the system anymore if ex.winerror == ERROR_INVALID_PARAMETER: raise ValueError("Invalid PID: {0:d}".format(pid)) # Other kind of exception raise ex finally: if handle is not None: win32api.CloseHandle(handle)
def __kill(self, service_type): service_list = wmi.WMI().Win32_Service(DisplayName = self.get_service_name(service_type)) if service_list: for service in service_list: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, service.ProcessId) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle)
def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # stop the running OpenERP Web: say it's a normal exit win32api.TerminateProcess(int(self.openerp_process._handle), 0) servicemanager.LogInfoMsg("OpenERP Web stopped correctly") # And set my event. win32event.SetEvent(self.hWaitStop)
def kill(pid): if arch == "amd64": os.system("taskkill /pid %s /t /f" % (pid)) else: handle = win32api.OpenProcess(1, False, pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) return True