def kill_service(service, install_root):
    pidfile = os.path.join(install_root, service, "pids", "pidfile")
    with open(pidfile) as f:
        pids = f.read().splitlines()
        for pid in pids:
            sh.kill('-9', pid)

    os.remove(pidfile)
示例#2
0
 def stop(self):
     print('Stopping service: ', self.name)
     if settings.TEST_SERVER == 'localhost':
         pids = sh.pgrep('-f', 'manage.py runserver', _ok_code=[0, 1])
         for pid in pids:
             sh.kill(pid.rstrip())
     else:
         sh.ssh(settings.TEST_SERVER, 'sudo supervisorctl stop all')
示例#3
0
    def tearDown(self):
        # Stop HPE Docker Plugin
        kill(str(self.twistd_pid))

        is_running = os.path.exists("/proc/%s" % str(self.twistd_pid))
        while is_running:
            is_running = os.path.exists("/proc/%s" % str(self.twistd_pid))
            time.sleep(0.25)
示例#4
0
 def _stop_celery(self):
     processes = self._info_celery()
     print(processes.keys())
     for pid in processes:
         try:
             sh.kill("-9", str(pid))
         except:
             print(pid, " process already deleted")
示例#5
0
    def stop(self):
        ''' Stop proxy '''

        self.namespace.log.debug('stop {}'.format(self))
        try:
            self.namespace.log.debug('kill -HUP {}'.format(pid))
            sh.kill('-HUP', self.pid)
        except:
            pass
示例#6
0
def is_alive(pidfile):
    if os.path.exists(pidfile):
        with open(pidfile, "rb") as fp:
            pid = fp.read()
        try:
            kill("-0", pid)
            return True
        except ErrorReturnCode:
            return False
    return False
def is_alive(pidfile):
    if os.path.exists(pidfile):
        with open(pidfile, 'rb') as fp:
            pid = fp.read()
        try:
            sh.kill('-0', pid.strip())
            return True
        except ErrorReturnCode:
            return False
    return False
def test_gerador_lero_lero():
    '''
    idem ao teste anterior
    '''
    gerador_filename = abspath(join(dirname(__file__), '../gerador_lero_lero.py'))
    sh.env('python', gerador_filename, _bg=True)
    pid = get_pid(gerador_filename)
    assert pid
    sh.kill(pid)
    assert not get_pid(gerador_filename)
示例#9
0
    def KillProcess(self, signal="-9"):
        """This function kills the process with default signal -9.

      This function uses by default, -SIGKILL or -9 signal to kill the
      processes, but it does not recursively kill the process-tree
    Args:
      signal: optional. Needed if you want to specify a particular kill signal.
      default is -9/-SIGKILL
    """
        sh.kill(signal, self.pid, _out=self.os)
示例#10
0
文件: manage.py 项目: guokr/asynx
def reload():
    """Reloading the restful server"""
    g = _gunicorn()
    if not os.path.isfile(g.PIDFILE):
        print('pidfile "{0}" is not found'.format(g.PIDFILE),
              file=sys.stderr)
        return 1
    print('Reloading asynxd:', end=' ')
    with open(g.PIDFILE) as fp:
        sh.kill('-HUP', fp.read().strip(), **_shkw)
    say_ok()
示例#11
0
def restart():
    pids = set(sh.pgrep("-f", "borgmacator").stdout.decode().splitlines())
    pids.discard(str(os.getpid()))
    if pids:
        sh.kill(*pids)
    p = sh.dbus_send(
        "--session", "--type=method_call", "--dest=org.gnome.Shell",
        "/org/gnome/Shell", "org.gnome.Shell.Eval",
        "string:'const Util = imports.misc.util; Util.spawnCommandLine(\"%s\");'"
        % sh.which("borgmacator"))
    print("Run the following if borgmacator didn't start")
    print(b" ".join(p.cmd).decode())
def test_app():
    '''
    pid não é obtido corretamente quando o teste é executado,
    mas funciona durante depuração
    '''
    app_filename = abspath(join(dirname(__file__), '../app.py'))
    sh.env('python', app_filename, _bg=True)
    pid = get_pid(app_filename)
    assert pid
    sh.kill('-s', 'SIGUSR1', pid)
    assert get_pid(app_filename)
    sh.kill(pid)
    assert not get_pid(app_filename)
示例#13
0
    def _stop_bot(self, param):

        action_result = self.add_action_result(phantom.ActionResult(dict(param)))

        pid = self._state.get('pid', '')
        if pid:

            self._state.pop('pid')

            try:
                if 'slack_bot.pyc' in sh.ps('ww', pid):  # pylint: disable=E1101
                    sh.kill(pid)  # pylint: disable=E1101
                    action_result.set_status(phantom.APP_SUCCESS, "SlackBot has been stopped.")

            except:
                action_result.set_status(phantom.APP_SUCCESS, "SlackBot isn't running, not going to stop it.")

        else:
            action_result.set_status(phantom.APP_SUCCESS, "SlackBot isn't running, not going to stop it.")

        rest_url = consts.SLACK_PHANTOM_ASSET_INFO_URL.format(url=self.get_phantom_base_url(), asset_id=self.get_asset_id())

        ret_val, resp_json = self._make_rest_call(action_result, rest_url, False)

        if phantom.is_fail(ret_val):
            return ret_val

        asset_config = resp_json.get('configuration', {})

        ingest_config = asset_config.get('ingest', {})

        poll = ingest_config.get('poll')

        if poll is None:
            return action_result.set_status(phantom.APP_SUCCESS, "{} Failed to disable ingestion, please check that ingest settings are correct."
                    .format(action_result.get_message()))

        if not poll:
            return action_result.set_status(phantom.APP_SUCCESS, "{} Ingestion isn't enabled, not going to disable it.".format(action_result.get_message()))

        ingest_config['poll'] = False

        body = {'configuration': asset_config}

        ret_val, resp_json = self._make_rest_call(action_result, rest_url, False, method=requests.post, body=body)

        if phantom.is_fail(ret_val):
            return ret_val

        return action_result.set_status(phantom.APP_SUCCESS, "{} Ingestion has been disabled.".format(action_result.get_message()))
示例#14
0
    def close(self):
        try:
            pid = self.get_remote_ssh_pid()
        except EnvError:
            pass
        else:
            print(f'closing pid {pid}', file=sys.stderr)
            sh.kill(pid)

        self.remove_socket()

        self.print_eval_hint()

        print(f'unset DOCKER_HOST')
示例#15
0
    def connect(self, essid, key):
        try:
            from sh import dhcpcd as dhcp
        except CommandNotFound:
            from sh import dhclient as dhcp
        if self._dhcpcd_pid is not None:
            kill(self._dhcpcd_pid)

        iwconfig(self.dev, 'essid', essid)
        iwconfig(self.dev, 'key', key)
        for line in dhcp(self.dev, _err_to_out, _iter=True):
            m = ManagedInterface._DHCPCD_SUCCESS_LINE.match(line)
            if m is not None:
                self._dhcpcd_pid = m.group(1)
                return True
        return False
示例#16
0
    def connect(self, essid, key):
        try:
            from sh import dhcpcd as dhcp
        except CommandNotFound:
            from sh import dhclient as dhcp
        if self._dhcpcd_pid is not None:
            kill(self._dhcpcd_pid)

        iwconfig(self.dev, 'essid', essid)
        iwconfig(self.dev, 'key', key)
        for line in dhcp(self.dev, _err_to_out, _iter=True):
            m = ManagedInterface._DHCPCD_SUCCESS_LINE.match(line)
            if m is not None:
                self._dhcpcd_pid = m.group(1)
                return True
        return False
示例#17
0
    def kill(self):
        #
        # this is not working, as we do not jet use subprocess
        #
        if self.data['pid'] is not None:
            self.data['pid'].terminate()
            self.data['pid'] = None

        #
        # TODO: this is not a good way to kill, as it apears that we only read 80 chars for each line in ps
        #
        result = sh.ps("-o", "pid,command", _tty_in=False, _tty_out=False)
        for line in result.split("\n"):
            if "notebook" in line and "ipython" in line:
                attributes = line.strip().split(' ')
                pid = attributes[0]
                print("TERMINATING", pid)
                sh.kill("-9", pid)
示例#18
0
def dhclient(iface, enable, script=None):
    # Disable the dhcp client and flush interface
    try:
        dhclients = sh.awk(
            sh.grep(sh.grep(sh.ps("ax"), iface, _timeout=5),
                    "dhclient",
                    _timeout=5), "{print $1}")
        dhclients = dhclients.split()
        for dhclient in dhclients:
            sh.kill(dhclient)
    except Exception as e:
        _logger.info("Failed to stop dhclient: %s" % e)
        pass

    if enable:
        if script:
            sh.dhclient("-nw", "-sf", script, iface, _bg=True)
        else:
            sh.dhclient("-nw", iface, _bg=True)
示例#19
0
def dhclient(iface, enable, script=None):
    # Disable the dhcp client and flush interface
    try:
        dhclients = sh.awk(
            sh.grep(
                sh.grep(sh.ps("ax"), iface, _timeout=5),
                "dhclient", _timeout=5),
            "{print $1}")
        dhclients = dhclients.split()
        for dhclient in dhclients:
            sh.kill(dhclient)
    except Exception as e:
        _logger.info("Failed to stop dhclient: %s" % e)
        pass

    if enable:
        if script:
            sh.dhclient("-nw", "-sf", script, iface, _bg=True)
        else:
            sh.dhclient("-nw", iface, _bg=True)
示例#20
0
    def _stop_web_server(self):
        # stop web server
        banner("stop the web server")
        try:
            result = sh.fgrep(
                sh.fgrep(self._ps(), "python {name}.py".format(**self.server_env)),
                "-v", "fgrep"
            ).split("\n")[:-1]
            print(result)

            for line in result:
                if line is not '':
                    pid = line.split(" ")[0]
                    print(line)
                    print("PID", pid)
                    print("KILL")
                    try:
                        sh.kill("-9", str(pid))
                    except Exception, e:
                        print("ERROR")
                        print(e)
        except Exception, e:
            print("INFO: cloudmesh web server not running")
示例#21
0
    def handle(self):
        self.data = self.request.recv(1024).strip()

        if(self.data == "status"):
            logging.info("Statusrequest from {}".format(self.client_address[0]))
            processes = ('xloader', '')
            statuses = {}
            for proc in processes:
                statuses[proc] = processcheck(proc)
            
            self.request.sendall(json.dumps(statuses))
            
        elif self.data == "killview":
            sh.killall('omxplayer.bin', _ok_code=[1])
            sh.killall('mplayer', _ok_code=[1])
            sh.kill(find_pid('python', 'viewer.py'))
            self.request.sendall(json.dumps("OK"))
                
        else:
            logging.debug("{} wrote:".format(self.client_address[0]))
            logging.debug(str(self.data))
            # just send back the same data, but upper-cased
            self.request.sendall("your string in caps: {}".format(self.data.upper()))
示例#22
0
    def _on_poll(self, param):

        action_result = self.add_action_result(phantom.ActionResult(dict(param)))

        ret_val, resp_json = self._make_slack_rest_call(action_result, consts.SLACK_AUTH_TEST, {})

        if not ret_val:
            return ret_val

        bot_id = resp_json.get('user_id')

        if not bot_id:
            return action_result.set_status(phantom.APP_ERROR, "Could not get bot ID from Slack")

        pid = self._state.get('pid', '')

        if pid:

            try:
                if 'slack_bot.pyc' in sh.ps('ww', pid):  # pylint: disable=E1101
                    self.save_progress("Detected SlackBot running with pid {0}".format(pid))
                    return action_result.set_status(phantom.APP_SUCCESS, "SlackBot already running")
            except:
                pass

        config = self.get_config()
        bot_token = config.get('bot_token', '')
        ph_auth_token = config.get('ph_auth_token', None)

        if not ph_auth_token:
            return action_result.set_status(phantom.APP_ERROR, "The ph_auth_token asset configuration parameter is required to run the on_poll action.")

        app_version = self.get_app_json().get('app_version', '')

        try:
            ps_out = sh.grep(sh.ps('ww', 'aux'), 'slack_bot.pyc')  # pylint: disable=E1101

            if app_version not in ps_out:

                old_pid = shlex.split(str(ps_out))[1]

                self.save_progress("Found an old version of slackbot running with pid {}, going to kill it".format(old_pid))

                sh.kill(old_pid)  # pylint: disable=E1101

        except:
            pass

        try:
            if bot_token in sh.grep(sh.ps('ww', 'aux'), 'slack_bot.pyc'):  # pylint: disable=E1101
                return action_result.set_status(phantom.APP_ERROR, "Detected an instance of SlackBot running with the same bot token. Not going to start new instance.")

        except:
            pass

        self.save_progress("Starting SlackBot")

        ret_val, base_url = self._get_phantom_base_url_slack(action_result)

        if phantom.is_fail(ret_val):
            return ret_val

        slack_bot_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'slack_bot.pyc')

        base_url += '/' if not base_url.endswith('/') else ''

        proc = subprocess.Popen(['phenv', 'python2.7', slack_bot_filename, bot_token, bot_id, base_url, app_version, ph_auth_token])

        self._state['pid'] = proc.pid

        self.save_progress("Started SlackBot with pid: {0}".format(proc.pid))

        return action_result.set_status(phantom.APP_SUCCESS, "SlackBot started")
示例#23
0
def kill_bots():
    for line in sh.ps.auxw().splitlines():
        if "src/main" in line:
            pid = line.split()[1]
            if pid.isnumeric():
                sh.kill(pid)
示例#24
0
    def _stop_bot(self, param):

        action_result = self.add_action_result(
            phantom.ActionResult(dict(param)))

        pid = self._state.get('pid', '')
        if pid:

            self._state.pop('pid')

            try:
                if 'slack_bot.pyc' in sh.ps('ww', pid):  # pylint: disable=E1101
                    sh.kill(pid)  # pylint: disable=E1101
                    action_result.set_status(phantom.APP_SUCCESS,
                                             SLACK_SUCC_SLACKBOT_STOPPED)

            except:
                action_result.set_status(phantom.APP_SUCCESS,
                                         SLACK_SUCC_SLACKBOT_NOT_RUNNING)

        else:
            action_result.set_status(phantom.APP_SUCCESS,
                                     SLACK_SUCC_SLACKBOT_NOT_RUNNING)

        rest_url = SLACK_PHANTOM_ASSET_INFO_URL.format(
            url=self.get_phantom_base_url(), asset_id=self.get_asset_id())

        ret_val, resp_json = self._make_rest_call(action_result, rest_url,
                                                  False)

        if phantom.is_fail(ret_val):
            return ret_val

        asset_config = resp_json.get('configuration', {})

        ingest_config = asset_config.get('ingest', {})

        poll = ingest_config.get('poll')

        if poll is None:
            return action_result.set_status(
                phantom.APP_SUCCESS,
                SLACK_FAILED_TO_DISABLE_INGESTION.format(
                    message=action_result.get_message()))

        if not poll:
            return action_result.set_status(
                phantom.APP_SUCCESS,
                SLACK_INGESTION_NOT_ENABLED.format(
                    message=action_result.get_message()))

        ingest_config['poll'] = False

        body = {'configuration': asset_config}

        ret_val, resp_json = self._make_rest_call(action_result,
                                                  rest_url,
                                                  False,
                                                  method=requests.post,
                                                  body=body)

        if phantom.is_fail(ret_val):
            return ret_val

        return action_result.set_status(
            phantom.APP_SUCCESS,
            SLACK_INGESTION_DISABLED.format(
                message=action_result.get_message()))
示例#25
0
 def kill_server(self, args):
     try: 
         log("Killing the server with pid : " + args.kill)
         kill("-9", "args.kill")
     except:
         log("Killing the server with pid : " + args.kill)
示例#26
0
def killId(id, num):
    kill('-%d' % num, id)
示例#27
0
 def kill(self):
     time.sleep(2)
     print("5second")
     hello = os.getpid()
     a = sh.kill()
     a(_in=hello)
示例#28
0
    with open(pids_file, 'r') as f:
        pids = json.loads(f.read())
        on_off = 'off'
        already_sexy = True

if len(argv) > 1:
    on_off = argv[1]

def run_command(command, command_index):
    with open(os.devnull, 'r+b', 0) as DEVNULL:
        p = Popen(command, stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, preexec_fn=os.setpgrp)
    set_pid(command_index, p.pid)

def set_pid(command, pid):
    pids[command] = pid

if on_off == 'off':
    with suppress(ErrorReturnCode_1):
        rm(pids_file)
        for pid in pids:
            kill(pid)

elif not already_sexy:
    for i, command in enumerate(commands):
        Thread(target=run_command, args=[command, i]).start()

    sleep(0.1)
    with open(pids_file, 'w+') as f:
        pids = json.dumps(pids)
        f.write(pids)
示例#29
0
def grunt_stop(site):
    """Stop grunt watch"""
    puts("Stopping Grunt watch")
    sh.kill(site.grunt_pid)
示例#30
0
def grunt_stop(site):
    """Stop grunt watch"""
    puts("Stopping Grunt watch")
    sh.kill(site.grunt_pid)
示例#31
0
文件: kill.py 项目: xuender/ubuntu
def killId(id, num):
    kill('-%d'%num, id)
示例#32
0
    def _on_poll(self, param):

        action_result = self.add_action_result(
            phantom.ActionResult(dict(param)))

        ret_val, resp_json = self._make_slack_rest_call(
            action_result, SLACK_AUTH_TEST, {})

        if not ret_val:
            return ret_val

        bot_id = resp_json.get('user_id')

        if not bot_id:
            return action_result.set_status(phantom.APP_ERROR,
                                            SLACK_ERR_COULD_NOT_GET_BOT_ID)

        pid = self._state.get('pid', '')

        if pid:

            try:
                if 'slack_bot.pyc' in sh.ps('ww', pid):  # pylint: disable=E1101
                    self.save_progress(
                        "Detected SlackBot running with pid {0}".format(pid))
                    return action_result.set_status(
                        phantom.APP_SUCCESS, SLACK_SUCC_SLACKBOT_RUNNING)
            except:
                pass

        config = self.get_config()
        bot_token = config.get('bot_token', '')
        ph_auth_token = config.get('ph_auth_token', None)

        if not ph_auth_token:
            return action_result.set_status(phantom.APP_ERROR,
                                            SLACK_ERR_AUTH_TOKEN_NOT_PROVIDED)

        app_version = self.get_app_json().get('app_version', '')

        try:
            ps_out = sh.grep(sh.ps('ww', 'aux'), 'slack_bot.pyc')  # pylint: disable=E1101

            if app_version not in ps_out:

                old_pid = shlex.split(str(ps_out))[1]

                self.save_progress(
                    "Found an old version of slackbot running with pid {}, going to kill it"
                    .format(old_pid))

                sh.kill(old_pid)  # pylint: disable=E1101

        except:
            pass

        try:
            if bot_token in sh.grep(sh.ps('ww', 'aux'), 'slack_bot.pyc'):  # pylint: disable=E1101
                return action_result.set_status(
                    phantom.APP_ERROR,
                    SLACK_ERR_SLACKBOT_RUNNING_WITH_SAME_BOT_TOKEN)

        except:
            pass

        self.save_progress("Starting SlackBot")

        ret_val, base_url = self._get_phantom_base_url_slack(action_result)

        if phantom.is_fail(ret_val):
            return ret_val

        slack_bot_filename = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'slack_bot.pyc')

        base_url += '/' if not base_url.endswith('/') else ''

        proc = subprocess.Popen([
            'phenv', 'python2.7', slack_bot_filename, bot_token, bot_id,
            base_url, app_version, ph_auth_token
        ])

        self._state['pid'] = proc.pid

        self.save_progress("Started SlackBot with pid: {0}".format(proc.pid))

        return action_result.set_status(phantom.APP_SUCCESS,
                                        SLACK_SUCC_SLACKBOT_STARTED)
示例#33
0
import sh

things = sh.kill('--table').split()
signals = {}
while things:
    signals[things.pop(0)] = things.pop(0)

print('#include <string.h>')

print('int signalstr(const char* arg) {')
print('    if(!arg) return -1;')

for sig,num in signals.items():
    print('    if(0==strcasecmp(arg,"{}")) return {};'.format(sig,num))

print('return -1;')
print('}')