Python kill process

60 Python code examples are found related to " kill process". 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.
Example 1
Source File: routes.py    From VectorCloud with GNU General Public License v3.0 7 votes vote down vote up
def kill_process(pid):
    application = Application.query.filter_by(pid=pid).first()

    if application:
        application.pid = None
        db.session.commit()

    try:
        os.kill(int(pid), signal.SIGINT)
        flash('Process Killed!', 'success')

    except ProcessLookupError:
        flash('Process has already ended or is not found.', 'warning')

    return redirect(url_for('main.home'))


# this deletes an application by it's unique key (id column). This will delete:
# 1. the main python file
# 2. image file (if not default)
# 3. any added support files associated with the hex id
# 4. database entries for all of the above 
Example 2
Source File: __init__.py    From ACE with Apache License 2.0 6 votes vote down vote up
def kill_process_tree(pid, sig=signal.SIGTERM, include_parent=True,
                      timeout=None, on_terminate=None):
    """Kill a process tree (including grandchildren) with signal
    "sig" and return a (gone, still_alive) tuple.
    "on_terminate", if specified, is a callabck function which is
    called as soon as a child terminates.
    """

    if pid == os.getpid():
        raise RuntimeError("I refuse to kill myself")

    parent = psutil.Process(pid)
    children = parent.children(recursive=True)
    if include_parent:
        children.append(parent)

    for p in children:
        p.send_signal(sig)

    gone, alive = psutil.wait_procs(children, timeout=timeout,
                                    callback=on_terminate)
    return (gone, alive) 
Example 3
Source File: new_process.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def kill_process_tree(root_pid):
  """Kill process tree."""
  try:
    parent = psutil.Process(root_pid)
    children = parent.children(recursive=True)
  except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
    logs.log_warn('Failed to find or access process.')
    return

  for child in children:
    try:
      child.kill()
    except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
      logs.log_warn('Failed to kill process child.')

  try:
    parent.kill()
  except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):
    logs.log_warn('Failed to kill process.') 
Example 4
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
def kill_process_by_name(self, process_name: str = 'apache2') -> bool:
        """
        Kill process by name
        :param process_name: Process name string (default: apache2)
        :return: True if kill process or False if not
        """
        if self.get_platform().startswith('Windows'):
            sub.check_output('taskkill /F /IM ' + process_name, shell=True)
            return True
        else:
            process_pid = self.get_process_pid(process_name)
            if process_pid != -1:
                while (self.get_process_pid(process_name) != -1):
                    self.kill_process(process_pid)
                return True
            else:
                return False 
Example 5
Source File: job_utils.py    From FATE with Apache License 2.0 6 votes vote down vote up
def kill_task_executor_process(task: Task, only_child=False):
    try:
        pid = int(task.f_run_pid)
        if not pid:
            return False
        schedule_logger(task.f_job_id).info("try to stop job {} task {} {} {} process pid:{}".format(
            task.f_job_id, task.f_task_id, task.f_role, task.f_party_id, pid))
        if not check_job_process(pid):
            return True
        p = psutil.Process(int(pid))
        if not is_task_executor_process(task=task, process=p):
            schedule_logger(task.f_job_id).warning("this pid {} is not task executor".format(pid))
            return False
        for child in p.children(recursive=True):
            if check_job_process(child.pid) and is_task_executor_process(task=task, process=child):
                child.kill()
        if not only_child:
            if check_job_process(p.pid) and is_task_executor_process(task=task, process=p):
                p.kill()
        return True
    except Exception as e:
        raise e 
Example 6
Source File: agent.py    From shakedown with Apache License 2.0 6 votes vote down vote up
def kill_process_on_host(
    hostname,
    pattern
):
    """ Kill the process matching pattern at ip

        :param hostname: the hostname or ip address of the host on which the process will be killed
        :param pattern: a regular expression matching the name of the process to kill
    """

    status, stdout = run_command_on_agent(hostname, "ps aux | grep -v grep | grep '{}'".format(pattern))
    pids = [p.strip().split()[1] for p in stdout.splitlines()]

    for pid in pids:
        status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
        if status:
            print("Killed pid: {}".format(pid))
        else:
            print("Unable to killed pid: {}".format(pid)) 
Example 7
Source File: convert_stix.py    From cti-stix-elevator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_kill_chain(kc):
    for kcp in kc.kill_chain_phases:
        # Use object itself as key.
        if kcp.phase_id:
            _KILL_CHAINS_PHASES[kcp.phase_id] = {"kill_chain_name": kc.name, "phase_name": kcp.name}
        else:
            _KILL_CHAINS_PHASES[kcp] = {"kill_chain_name": kc.name, "phase_name": kcp.name}


#
# identities
#


# def get_simple_name_from_identity(identity, bundle_instance, sdo_instance):
#     if isinstance(identity, CIQIdentity3_0Instance):
#         handle_relationship_to_refs([identity], sdo_instance["id"], bundle_instance, "attributed-to")
#     else:
#         return identity.name 
Example 8
Source File: shell.py    From st2 with Apache License 2.0 6 votes vote down vote up
def kill_process(process):
    """
    Kill the provided process by sending it TERM signal using "pkill" shell
    command.

    Note: This function only works on Linux / Unix based systems.

    :param process: Process object as returned by subprocess.Popen.
    :type process: ``object``
    """
    kill_command = shlex.split('sudo pkill -TERM -s %s' % (process.pid))

    try:
        if six.PY3:
            status = subprocess.call(kill_command, timeout=100)  # pylint: disable=not-callable
        else:
            status = subprocess.call(kill_command)  # pylint: disable=not-callable
    except Exception:
        LOG.exception('Unable to pkill process.')

    return status 
Example 9
Source File: kalipi.py    From Kali-Pi with GNU General Public License v3.0 6 votes vote down vote up
def kill_process(proc, file=":"):
    try:
        check = "ps auxww | grep [" + proc[0] + "]" + proc[1:] + " | grep " + file
        status = commands.getoutput(check)
        #print(status)
        if status:
            #Process exists, kill it
            kill = "kill $(" + check + " | awk '{print $2}')"
            commands.getoutput(kill)
            return True
        else:
            return False
    except:
        return False

#This function is used to check individual processes, not services. 
Example 10
Source File: process.py    From pyngrok with MIT License 6 votes vote down vote up
def kill_process(ngrok_path):
    """
    Terminate the :code:`ngrok` processes, if running, for the given path. This method will not block, it will just
    issue a kill request.

    :param ngrok_path: The path to the :code:`ngrok` binary.
    :type ngrok_path: str
    """
    if ngrok_path in _current_processes:
        ngrok_process = _current_processes[ngrok_path]

        logger.info("Killing ngrok process: {}".format(ngrok_process.proc.pid))

        try:
            ngrok_process.proc.kill()
        except OSError as e:
            # If the process was already killed, nothing to do but cleanup state
            if e.errno != 3:
                raise e

        _current_processes.pop(ngrok_path, None)
    else:
        logger.debug("\"ngrok_path\" {} is not running a process".format(ngrok_path)) 
Example 11
Source File: bigfix_client.py    From resilient-community-apps with MIT License 6 votes vote down vote up
def send_kill_process_remediation_message(self, artifact_value, computer_id):
        """ Bigfix action - Kill process remediate action.

        :param artifact_value: Name of artifact to remediate
        :param computer_id: BigFix Endpoint id
        :return resp: Response from action

        """
        query = "if {{windows of operating system}} \n waithidden cmd.exe /c taskkill /im {0} /f /t \n" \
                "else \n wait kill -9  {{concatenation \" \" of (ids of processes whose (name of it = \"{0}\") as string)}}\n " \
                "endif".format(artifact_value)
        relevance = "if (windows of operating system) " \
                    "then (exists process whose(name of it as lowercase = \"{0}\" as lowercase)) " \
                    "else if (name of it contains \"Linux\") of operating system " \
                    "then (exists process whose(name of it = \"{0}\")) else (false)".format(artifact_value)
        return self._post_bf_action_query(query, computer_id, "Kill Process '{0}'".format(artifact_value), relevance) 
Example 12
Source File: server.py    From storlets with Apache License 2.0 6 votes vote down vote up
def process_kill_all(self, try_all=True):
        """
        Kill every one.

        :param try_all: wheather we try to kill all process if we fail to
                        stop some of the storlet daemons
        :raises SDaemonError: when failed to kill one of the storlet daemons
        """
        failed = []
        for storlet_name in list(self.storlet_name_to_pid):
            try:
                self.process_kill(storlet_name)
            except SDaemonError:
                self.logger.exception('Failed to stop the storlet daemon {0}'
                                      .format(storlet_name))
                if try_all:
                    failed.append(storlet_name)
                else:
                    raise
        if failed:
            names = ', '.join(failed)
            raise SDaemonError('Failed to stop some storlet daemons: {0}'
                               .format(names)) 
Example 13
Source File: event_handlers.py    From aws-builders-fair-projects with Apache License 2.0 6 votes vote down vote up
def process_kill_request(debug_mode=None, image_dir=""):

	process_logger = logging.getLogger('cerebro_processor.process_kill_request')

	#slideshow_util_stop = "../scripts/stop-picture-frame.sh"
	slideshow_util_stop = "../scripts/stop-slideshow-only.sh"
	slideshow_log_stop = "%s/picframe.stop.log" % config.__CEREBRO_LOGS_DIR__

	if debug_mode:
		process_logger.info("Killing the monitor process now. ignore all other parameters.")
		return True

	else:
		process_logger.info("Killing the monitor process now. Breaking out of the loop now ...")
		delete_local_files(image_dir=image_dir)
		status = subprocess.call(
			'%s > %s 2>&1 &' % 
			(slideshow_util_stop, slideshow_log_stop), 
			shell=True)
		return True

	process_logger.error("Error! Invalid DebugMode!!")
	return False 
Example 14
Source File: linux.py    From zstack-utility with Apache License 2.0 6 votes vote down vote up
def kill_process(pid, timeout=5):
    def check(_):
        return not os.path.exists('/proc/%s' % pid)

    if check(None):
        return

    logger.debug("kill -15 process[pid %s]" % pid)
    os.kill(int(pid), 15)

    if wait_callback_success(check, None, timeout):
        return

    logger.debug("kill -9 process[pid %s]" % pid)
    os.kill(int(pid), 9)
    if not wait_callback_success(check, None, timeout):
        raise Exception('cannot kill -9 process[pid:%s];the process still exists after %s seconds' % (pid, timeout)) 
Example 15
Source File: common.py    From rotest with MIT License 6 votes vote down vote up
def kill_process_tree(process):
    """Kill a process and all its subprocesses.

    Note:
        Kill the process and all its sub processes recursively.
        If the given process is the current process - Kills the sub process
        before the given process. Otherwise - Kills the given process before
        its sub processes

    Args:
        process (psutil.Process): process to kill.
    """
    sub_processes = process.children(recursive=True)

    if process.pid == os.getpid():
        for sub_process in sub_processes:
            kill_process(sub_process)

        kill_process(process)

    else:
        kill_process(process)

        for sub_process in sub_processes:
            kill_process(sub_process) 
Example 16
Source File: common.py    From rotest with MIT License 6 votes vote down vote up
def kill_process(process):
    """Kill a single process.

    Args:
        process (psutil.Process): process to kill.
    """
    if not process.is_running():
        return

    process.kill()

    try:
        process.wait(PROCESS_TERMINATION_TIMEOUT)

    except psutil.TimeoutExpired:
        core_log.warning("Process %d failed to terminate", process.pid) 
Example 17
Source File: labview.py    From python_labview_automation with MIT License 5 votes vote down vote up
def kill_process(self, pid, executable, timeout=None):
        proc = self._get_process(pid, executable)
        if proc is None:
            return  # Process not running, just exit.
        proc.kill()
        proc.wait(timeout) 
Example 18
Source File: take_backup.py    From MySQL-AutoXtraBackup with MIT License 5 votes vote down vote up
def check_kill_process(pstring):
        # Static method for killing given processes
        for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
            fields = line.split()
            pid = fields[0]
            if pid:
                os.kill(int(pid), signal.SIGKILL) 
Example 19
Source File: deployer.py    From Zopkio with Apache License 2.0 5 votes vote down vote up
def kill_all_process(self):
    """ Terminates all the running processes

    """
    pass 
Example 20
Source File: procfeedback.py    From codimension with GNU General Public License v3.0 5 votes vote down vote up
def killProcess(pid):
    """Tries to kill the given process"""
    for signal in (SIGTERM, SIGINT, SIGHUP):
        if not isProcessAlive(pid):
            return

        try:
            os.kill(pid, signal)
        except OSError as excpt:
            if excpt.errno == errno.ESRCH:
                return  # Already dead
            raise
        time.sleep(0.5)

    # Could not kill gracefully, try harder
    startTime = time.time()
    while True:
        if not isProcessAlive(pid):
            return

        if time.time() - startTime >= 15:
            raise Exception("Cannot kill process (pid: " + str(pid) + ")")

        try:
            os.kill(pid, SIGKILL)
        except OSError as excpt:
            if excpt.errno == errno.ESRCH:
                return  # Already dead
            raise
        time.sleep(0.1) 
Example 21
Source File: deploy.py    From IPDC with MIT License 5 votes vote down vote up
def KillProcess(process):
	try:
                f = open('.ipfs/'+process+'.pid','r')
                while True:
                        line = f.readline()
                        if not line:
                                break
                        line = line.replace("\n","")
                        os.system("kill -9 "+line)
                        os.system("echo '' > .ipfs/"+process+".pid")
        except:
                pass 
Example 22
Source File: utils.py    From macro_pack with Apache License 2.0 5 votes vote down vote up
def forceProcessKill(processName):
    '''
    Force kill a process (only work on windows)
    '''
    os.system("taskkill /f /im  %s" % processName) 
Example 23
Source File: view.py    From sparta with GNU General Public License v3.0 5 votes vote down vote up
def killBruteProcess(self, bWidget):
		dbId = str(bWidget.display.property('dbId').toString())
		status = self.controller.getProcessStatusForDBId(dbId)
		if status == "Running":											# check if we need to kill or cancel
			self.controller.killProcess(self.controller.getPidForProcess(dbId), dbId)
			
		elif status == "Waiting":
			self.controller.cancelProcess(dbId)
		self.bruteProcessFinished(bWidget) 
Example 24
Source File: logic.py    From sparta with GNU General Public License v3.0 5 votes vote down vote up
def storeProcessKillStatusInDB(self, procId):
		proc = process.query.filter_by(id=procId).first()
		if proc and not proc.status == 'Finished':
			proc.status = 'Killed'
			proc.endtime = getTimestamp(True)	# store end time
			self.db.commit() 
Example 25
Source File: view.py    From sparta with GNU General Public License v3.0 5 votes vote down vote up
def killProcessConfirmation(self):
		message = "Are you sure you want to kill the selected processes?"
		reply = QtGui.QMessageBox.question(self.ui.centralwidget, 'Confirm', message, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
		if reply == QtGui.QMessageBox.Yes:
			return True
		return False

	### 
Example 26
Source File: controller.py    From sparta with GNU General Public License v3.0 5 votes vote down vote up
def killProcess(self, pid, dbId):
		print '[+] Killing process: ' + str(pid)	
		self.logic.storeProcessKillStatusInDB(str(dbId))				# mark it as killed
		try:
			os.kill(int(pid), signal.SIGTERM)
		except OSError:
			print '\t[-] This process has already been terminated.'
		except:
			print "\t[-] Unexpected error:", sys.exc_info()[0] 
Example 27
Source File: daemon.py    From mars with Apache License 2.0 5 votes vote down vote up
def kill_actor_process(self, actor_ref):
        """
        Kill a process given the ref of an actor on it
        """
        proc_idx = self.ctx.distributor.distribute(actor_ref.uid)
        try:
            pid = self._proc_pids[proc_idx]
            self._killed_pids.add(pid)
            kill_process_tree(pid)
        except (KeyError, OSError):
            pass 
Example 28
Source File: utils.py    From mars with Apache License 2.0 5 votes vote down vote up
def kill_process_tree(pid, include_parent=True):
    try:
        import psutil
    except ImportError:  # pragma: no cover
        return
    try:
        proc = psutil.Process(pid)
    except psutil.NoSuchProcess:
        return

    plasma_sock_dir = None
    children = proc.children(recursive=True)
    if include_parent:
        children.append(proc)
    for p in children:
        try:
            if 'plasma' in p.name():
                plasma_sock_dir = next((conn.laddr for conn in p.connections('unix')
                                        if 'plasma' in conn.laddr), None)
            p.kill()
        except psutil.NoSuchProcess:  # pragma: no cover
            pass
    if plasma_sock_dir:
        shutil.rmtree(plasma_sock_dir, ignore_errors=True) 
Example 29
Source File: util.py    From benchexec with Apache License 2.0 5 votes vote down vote up
def kill_process(pid, sig=None):
    """Try to send signal to given process."""
    if sig is None:
        sig = signal.SIGKILL  # set default lazily, otherwise importing fails on Windows
    try:
        os.kill(pid, sig)
    except OSError as e:
        if e.errno == errno.ESRCH:
            # process itself returned and exited before killing
            logging.debug(
                "Failure %s while killing process %s with signal %s: %s",
                e.errno,
                pid,
                sig,
                e.strerror,
            )
        else:
            logging.warning(
                "Failure %s while killing process %s with signal %s: %s",
                e.errno,
                pid,
                sig,
                e.strerror,
            ) 
Example 30
Source File: input_fn_tuning_job.py    From cloudml-samples with Apache License 2.0 5 votes vote down vote up
def kill_process(process):
    try:
        os.killpg(os.getpgid(process.pid), signal.SIGTERM)
    except:
        pass 
Example 31
Source File: utils_misc.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def kill_process_tree(pid, sig=signal.SIGKILL, send_sigcont=True, timeout=0):
    """Signal a process and all of its children.

    If the process does not exist -- return.

    :param pid: The pid of the process to signal.
    :param sig: The signal to send to the processes.
    :param send_sigcont: Send SIGCONT to allow destroying stopped processes
    :param timeout: How long to wait for the pid(s) to die
                    (negative=infinity, 0=don't wait,
                    positive=number_of_seconds)
    """
    try:
        return _kill_process_tree(pid, sig, send_sigcont, timeout)
    except TypeError:
        logging.warning("Trying to kill_process_tree with timeout but running"
                        " old Avocado without it's support. Sleeping for 10s "
                        "instead.")
        # Depending on the Avocado version this can either return None or
        # list of killed pids.
        ret = _kill_process_tree(pid, sig, send_sigcont)    # pylint: disable=E1128
        if timeout != 0:
            # Use fixed 10s wait when no support for timeout in Avocado
            time.sleep(10)
            if pid_exists(pid):
                raise RuntimeError("Failed to kill_process_tree(%s)" % pid)
        return ret 
Example 32
Source File: utils.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def kill_process(name):
    name += get_executable_extension()
    if is_windows():
        try:
            os.system("taskkill /im {} -F".format(name))
        except:
            log.exception("Failing killing old web2board process")
    else:
        # check whether the process name matches
        try:
            os.system("killall -9 {}".format(name))
        except:
            log.exception("Failing killing old web2board process") 
Example 33
Source File: common.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def kill_process(name):
  """Kill the process by its name."""
  plt = get_platform()
  if plt == 'windows':
    execute(
        'wmic process where (commandline like "%%%s%%") delete' % name,
        exit_on_error=False)
  elif plt in ['linux', 'macos']:
    execute('pkill -KILL -f "%s"' % name, exit_on_error=False) 
Example 34
Source File: vtrace_iface.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def kill_process(tr, kill=True):
  try:
    if kill:
      tr.kill()
    else:
      tr.detach()
  except:
    pass

#----------------------------------------------------------------------- 
Example 35
Source File: circo.py    From circo with MIT License 5 votes vote down vote up
def kill_process(pstring):
    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)


# Build SNMP OID Fake config 
Example 36
Source File: beer.py    From nematus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def kill_process(self):
        """
        Kills the BEER process right away.
        """
        self.beer_process.kill() 
Example 37
Source File: PlatformManagerWindows.py    From lackey with MIT License 5 votes vote down vote up
def killProcess(self, pid):
        """ Kills the process with the specified PID (if possible) """
        SYNCHRONIZE = 0x00100000
        PROCESS_TERMINATE = 0x0001
        hProcess = self._kernel32.OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, True, pid)
        result = self._kernel32.TerminateProcess(hProcess, 0)
        self._kernel32.CloseHandle(hProcess) 
Example 38
Source File: pymonitor.py    From python-webapp-blog with GNU General Public License v3.0 5 votes vote down vote up
def kill_process():
    global process
    if process:
        log('Kill process [%s]...' % process.pid)
        process.kill()
        process.wait()
        log('Process ended with code %s.' % process.returncode)
        process = None 
Example 39
Source File: gulp.py    From sublime-gulp with MIT License 5 votes vote down vote up
def kill_process(self, index=-1):
        if index >= 0 and index < len(self.procs):
            process = self.procs[index]
            try:
                process.kill()
            except ProcessLookupError as e:
                print('Process %d seems to be dead already' % process.pid)

            self.show_output_panel('')
            self.append_to_output_view("\n%s killed! # %s | PID: %d\n" % process.to_tuple()) 
Example 40
Source File: interactive.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def kill_process(self, pid):
        process = self.debug.system.get_process(pid)
        try:
            process.kill()
            if self.debug.is_debugee(pid):
                self.debug.detach(pid)
            print("Killed process (%d)" % pid)
        except Exception:
            print("Error trying to kill process (%d)" % pid)

    # Kill a thread. 
Example 41
Source File: process.py    From QMusic with GNU Lesser General Public License v2.1 5 votes vote down vote up
def kill_process(proc):
    '''
    Kill process.

    @param proc: Subprocess instance.
    '''
    try:
        if proc != None:
            proc.kill()
    except Exception, e:
        print "function kill_process got error: %s" % (e)
        traceback.print_exc(file=sys.stdout) 
Example 42
Source File: KillProcessHoldingPort.py    From ufora with Apache License 2.0 5 votes vote down vote up
def killProcessGroupHoldingPorts(portStart, portStop, retries = 5):
    toKillOrNone = pidAndProcessNameHoldingPorts(portStart, portStop)

    if toKillOrNone is None:
        return False

    pidToKill, processName = toKillOrNone

    try:
        pidGroupToKill = os.getpgid(pidToKill)

        logging.warn("Killing process group pgid=%s containing %s at pid=%s",
                pidGroupToKill,
                processName,
                pidToKill
                )

        os.killpg(pidGroupToKill, 9)
    except OSError:
        logging.warn("Failed to kill process holding port: %s.\n%s",
                     toKillOrNone, traceback.format_exc()
                     )

    toKillOrNone2 = pidAndProcessNameHoldingPorts(portStart, portStop)

    if toKillOrNone2 is not None:
        logging.error(
            "Failed to free the port range %s-%s. It was held as %s, now as %s",
            portStart,
            portStop,
            toKillOrNone,
            toKillOrNone2
            )
        if retries < 1:
            raise UserWarning("Failed to clear the port")
        logging.info("Trying to kill process group holding port range %s-%s again", portStart, portStop)
        return killProcessGroupHoldingPorts(portStart, portStop, retries-1)

    return True 
Example 43
Source File: blissflixx.py    From blissflixx with GNU General Public License v2.0 5 votes vote down vote up
def kill_process(name):
  s = subprocess.check_output("ps -ef | grep " + name, shell=True)
  lines = s.split('\n')
  for l in lines:
    items = l.split()
      # Don't kill our own command
    if len(items) > 2 and l.find("grep " + name) == -1:
      try:
        os.kill(int(items[1]), signal.SIGTERM)
      except Exception:
        pass 
Example 44
Source File: base.py    From raw-packet with MIT License 5 votes vote down vote up
def kill_process(self, process_pid: int) -> bool:
        """
        Kill process by ID
        :param process_pid: Process ID integer
        :return: True if kill process or False if not
        """
        try:
            if self.get_platform().startswith('Windows'):
                sub.check_output('taskkill /F /PID ' + str(process_pid), shell=True)
            else:
                process = ps.Process(process_pid)
                process.terminate()
            return True
        except ps.NoSuchProcess:
            return False 
Example 45
Source File: adb.py    From magneto with Apache License 2.0 5 votes vote down vote up
def kill_process(cls, package_name):
        """
        Stops given app::

            ADB.kill_process('com.android.chrome')

        :param str package_name: Package name to stop
        :return:
        """
        cls.exec_cmd("shell am force-stop {0}".format(package_name)).wait() 
Example 46
Source File: __main__.py    From openpyn-nordvpn with GNU General Public License v3.0 5 votes vote down vote up
def kill_openpyn_process() -> None:
    try:
        root.verify_root_access("Root access needed to kill openpyn process")
        subprocess.call(["sudo", "killall", "openpyn"])
    except subprocess.CalledProcessError:
        # when Exception, the openvpn_processes issued non 0 result, "not found"
        pass
    return 
Example 47
Source File: types.py    From simLAB with GNU General Public License v2.0 5 votes vote down vote up
def killProcess(name, signal=15):
    if os.name != 'posix':
        #cmd = 'taskkill /f /im ' + name
        cmd = 'taskkill /im /t' + name
    else:
        cmd = "killall -%d %s" %(signal, name)
    p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    return out,err 
Example 48
Source File: convert_stix.py    From cti-stix-slider with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_kill_chain_phases(phases, obj1x):
    for phase in phases:
        if phase["kill_chain_name"] in _KILL_CHAINS:
            kill_chain_phases = _KILL_CHAINS[phase["kill_chain_name"]]["phases"]
            if not phase["phase_name"] in kill_chain_phases:
                kill_chain_phases.update({phase["phase_name"]: KillChainPhase(
                    phase_id=create_id1x("TTP"),
                    name=phase["phase_name"],
                    ordinality=None)})
                _KILL_CHAINS[phase["kill_chain_name"]]["kill_chain"].add_kill_chain_phase(kill_chain_phases[phase["phase_name"]])
            kcp = kill_chain_phases[phase["phase_name"]]
            if not obj1x.kill_chain_phases:
                obj1x.kill_chain_phases = KillChainPhasesReference()
        else:
            kc = KillChain(id_=create_id1x("TTP"), name=phase["kill_chain_name"])
            _KILL_CHAINS[phase["kill_chain_name"]] = {"kill_chain": kc}
            kcp = KillChainPhase(name=phase["phase_name"], phase_id=create_id1x("TTP"))
            kc.add_kill_chain_phase(kcp)
            _KILL_CHAINS[phase["kill_chain_name"]]["phases"] = {phase["phase_name"]: kcp}
        obj1x.add_kill_chain_phase(KillChainPhaseReference(phase_id=kcp.phase_id,
                                                           name=kcp.name,
                                                           ordinality=None,
                                                           kill_chain_id=_KILL_CHAINS[phase["kill_chain_name"]][
                                                               "kill_chain"].id_,
                                                           kill_chain_name=_KILL_CHAINS[phase["kill_chain_name"]][
                                                               "kill_chain"].name)) 
Example 49
Source File: FidelisEndpoint.py    From content with MIT License 5 votes vote down vote up
def kill_process_by_pid(client: Client, args: dict) -> Tuple[str, Dict, Dict]:
    endpoint_ip = argToList(args.get('endpoint_ip'))
    endpoint_name = argToList(args.get('endpoint_name'))
    endpoint_id = get_endpoint_id(client, endpoint_ip, endpoint_name)
    time_out = args.get('time_out')
    operating_system = args.get('operating_system')
    pid = args.get('pid')
    script_id = ''

    if operating_system == 'Windows':
        script_id = KILL_PROCESS_WINDOWS

    elif operating_system == 'Linux' or operating_system == 'macOS':
        script_id = KILL_PROCESS_MAC_LINUX

    response = client.kill_process(script_id, pid, time_out, endpoint_id)
    if not response.get('success'):
        raise Exception(response.get('error'))
    job_id = response.get('data')
    context = {
        'ID': script_id,
        'JobID': job_id
    }
    entry_context = {'FidelisEndpoint.Process(val.ID && val.ID === obj.ID)': context}

    return f'The job has been executed successfully. \n Job ID: {job_id}', entry_context, response 
Example 50
Source File: FidelisEndpoint.py    From content with MIT License 5 votes vote down vote up
def kill_process(self, script_id: str = None, pid: int = None, time_out: int = None,
                     endpoint_ip=None) -> Dict:

        url_suffix = '/jobs/createTask'
        body = {
            'queueExpirationInhours': None,
            'wizardOverridePassword': False,
            'impersonationUser': None,
            'impersonationPassword': None,
            'priority': None,
            'timeoutInSeconds': time_out,
            'packageId': script_id,
            'endpoints': endpoint_ip,
            'isPlaybook': False,
            'taskOptions': [
                {
                    'integrationOutputFormat': None,
                    'scriptId': script_id,
                    'questions': [
                        {
                            'paramNumber': 1,
                            'answer': pid
                        }
                    ]
                }
            ]
        }

        return self._http_request('POST', url_suffix, json_data=body) 
Example 51
Source File: s_tui.py    From s-tui with GNU General Public License v2.0 5 votes vote down vote up
def kill_stress_process(self):
        """ Kills the current running stress process """
        try:
            kill_child_processes(self.stress_process)
        except psutil.NoSuchProcess:
            logging.debug("Stress process no longer exists")
        self.stress_process = None 
Example 52
Source File: procutils.py    From procexp with GNU General Public License v3.0 5 votes vote down vote up
def killProcess(process):
  try:
    os.kill(int(process), signal.SIGTERM)
  except OSError:
    pass 
Example 53
Source File: procexp.py    From procexp with GNU General Public License v3.0 5 votes vote down vote up
def killProcessTree(proc, procList):
  """ Kill a tree of processes, the hard way
  """
  killChildsTree(int(str(proc)), procList)
  utils.procutils.killProcessHard(int(str(proc))) 
Example 54
Source File: agent.py    From shakedown with Apache License 2.0 5 votes vote down vote up
def kill_process_from_pid_file_on_host(hostname, pid_file='app.pid'):
    """ Retrieves the PID of a process from a pid file on host and kills it.

    :param hostname: the hostname or ip address of the host on which the process will be killed
    :param pid_file: pid file to use holding the pid number to kill
    """
    status, pid = run_command_on_agent(hostname, 'cat {}'.format(pid_file))
    status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
    if status:
        print("Killed pid: {}".format(pid))
        run_command_on_agent(hostname, 'rm {}'.format(pid_file))
    else:
        print("Unable to killed pid: {}".format(pid)) 
Example 55
Source File: utils.py    From BentoML with Apache License 2.0 5 votes vote down vote up
def kill_process(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill() 
Example 56
Source File: utils.py    From cstar_perf with Apache License 2.0 5 votes vote down vote up
def find_and_kill_process(process_line, child_process=False):
    """Find a process and kill it"""

    pid = find_process_pid(process_line, child_process)
    kill_process(pid) 
Example 57
Source File: replicate_ms.py    From mysql-utilities with GNU General Public License v2.0 5 votes vote down vote up
def kill_process(self, proc, f_out, comment):
        """Kill process spwaned by subprocess.

        proc[in]          Subprocess process.
        f_out[in]         Output file.
        stop_phrase[in]   Phrase to be found.
        """
        # Need to poll here and wait for process to really end
        ret_val = stop_process(proc, True)
        if f_out and not f_out.closed:
            f_out.close()
        # Wait for process to end
        if self.debug:
            print("# Waiting for process to end.")
        i = 0
        while proc.poll() is None:
            time.sleep(1)
            i += 1
            if i > _TIMEOUT:
                if self.debug:
                    print("# Timeout process to end.")
                raise MUTLibError("{0}: failed - timeout waiting for "
                                  "process to end.".format(comment))

        if self.debug:
            print("# Return code from process termination = {0}"
                  "".format(ret_val)) 
Example 58
Source File: doa.py    From blackmamba with MIT License 5 votes vote down vote up
def kill_process(self):
        """Stop the process"""
        if self.process.poll() is not None:
            return
        try:
            if hasattr(self.process, 'terminate'):
                self.process.terminate()
            elif os.name != 'nt':
                os.kill(self.process.pid, 9)
            else:
                import ctypes
                handle = int(self.process._handle)
                ctypes.windll.kernel32.TerminateProcess(handle, -1)
        except OSError:
            pass 
Example 59
Source File: process.py    From ANALYSE with GNU Affero General Public License v3.0 5 votes vote down vote up
def kill_process(proc):
    """
    Kill the process `proc` created with `subprocess`.
    """
    p1_group = psutil.Process(proc.pid)

    child_pids = p1_group.get_children(recursive=True)

    for child_pid in child_pids:
        os.kill(child_pid.pid, signal.SIGKILL) 
Example 60
Source File: misc.py    From THRED with MIT License 5 votes vote down vote up
def kill_java_process(process_name):
    jps_cmd = subprocess.Popen('jps', stdout=subprocess.PIPE)
    jps_output = jps_cmd.stdout.read()
    pids = set()
    for jps_pair in jps_output.split(b'\n'):
        _p = jps_pair.split()
        if len(_p) > 1:
            if _p[1].decode() == process_name:
                pids.add(int(_p[0]))

    jps_cmd.wait()
    if pids:
        for pid in pids:
            os.kill(pid, SIGTERM)