python类NoSuchProcess()的实例源码

__init__.py 文件源码 项目:Chasar 作者: camilochs 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def pids_active(pids_computer):
    """
    This function find pids of computer and return the valid.
    """
    pid_valid = {}
    for pid in pids_computer:
        data = None
        try:
            process = psutil.Process(pid)
            data = {"pid": process.pid,
                    "status": process.status(),
                    "percent_cpu_used": process.cpu_percent(interval=0.0),
                    "percent_memory_used": process.memory_percent()}

        except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess):
            data = None

        if data is not None:
            pid_valid[process.name()] = data
    return pid_valid
console.py 文件源码 项目:ransomcare 作者: Happyholic1203 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def on_ask_user_allow_or_deny(self, evt):
        try:
            exe = evt.process.exe()
            cmdline = evt.process.cmdline()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            logger.warn('Ransomware process is caught, but the process does '
                        'not exist (PID: %d)' % evt.pid)

        logger.critical('\033[91m')
        logger.critical('*** [Crypto ransom detected] ***')
        logger.critical('[PID]: %d' % evt.process.pid)
        logger.critical('[EXE]: %r' % exe)
        logger.critical('[Command]: %r' % cmdline)
        logger.critical('[File]: %s' % evt.path)
        logger.critical('********************************\033[0m')
        flush_stdin()
        yes_no = raw_input('> Block it? (Y/n) ')

        allow = 'n' in yes_no.lower()
        if allow:
            event.EventUserAllowProcess(evt.process).fire()
        else:
            event.EventUserDenyProcess(evt.process).fire()
test_linux.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)
server.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def find_server_processes(cls, port=None):
        result = []
        for p in psutil.process_iter():
            try:
                if isinstance(type(p).cmdline, property):
                    pname = p.name
                    cmdline = p.cmdline
                else:
                    pname = p.name()
                    cmdline = p.cmdline()
                if pname == 'adb':
                    if 'fork-server' in cmdline and 'server' in cmdline:
                        if port != None and str(port) not in cmdline:
                            continue
                        result.append(p)
            except psutil.NoSuchProcess:
                continue
        return result
server.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def find_server_processes(cls, port=None):
        result = []
        for p in psutil.process_iter():
            try:
                if isinstance(type(p).cmdline, property):
                    pname = p.name
                    cmdline = p.cmdline
                else:
                    pname = p.name()
                    cmdline = p.cmdline()
                if pname == 'adb':
                    if 'fork-server' in cmdline and 'server' in cmdline:
                        if port != None and str(port) not in cmdline:
                            continue
                        result.append(p)
            except psutil.NoSuchProcess:
                continue
        return result
daemon.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def join(pid, timeout):
    if pid == 0:
        return
    start = time.time()
    while time.time() - start < timeout:
        try:
            proc = Process(pid)
        except NoSuchProcess:
            return
        except IOError, e:
            if e.errno == errno.ESRCH:
                return
            else:
                raise e
        time.sleep(0.5)
    raise Timeout('timeout')
daemon.py 文件源码 项目:ave 作者: sonyxperiadev 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def join(pid, timeout):
    if pid == 0:
        return
    start = time.time()
    while time.time() - start < timeout:
        try:
            proc = Process(pid)
        except NoSuchProcess:
            return
        except IOError, e:
            if e.errno == errno.ESRCH:
                return
            else:
                raise e
        time.sleep(0.5)
    raise Timeout('timeout')
process.py 文件源码 项目:monitorstack 作者: openstack 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def get_cmdlines():
    """Retrieve the cmdline of each process running on the system."""
    processes = []

    # Get our current PID as well as the parent so we can exclude them.
    current_pid = os.getpid()
    parent_pid = os.getppid()

    for proc in psutil.process_iter():
        try:
            if proc.pid not in [current_pid, parent_pid]:
                processes.append(' '.join(proc.cmdline()))
        except psutil.NoSuchProcess:
            pass

    return processes
daemon.py 文件源码 项目:aquests 作者: hansroh 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def kill (chdir, procname = None, include_children = True, signaling = True):
    import psutil

    for i in range (2):
        pid = status (chdir, procname)      
        if not pid: 
            break

        if signaling:   
            os.kill (pid, signal.SIGTERM)
            time.sleep (2)

        if include_children:
            try:
                killtree.kill (pid, True)
            except psutil.NoSuchProcess:
                pass    

        while processutil.is_running (pid, procname):
            time.sleep (1)

    try:
        os.remove (os.path.join (chdir, ".pid"))
    except FileNotFoundError:   
        pass
__init__.py 文件源码 项目:Chasar 作者: camilochs 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def pids_active(pids_computer):
    """
    This function find pids of computer and return the valid.
    """
    pid_valid = {}
    for pid in pids_computer:
        data = None
        try:
            process = psutil.Process(pid)
            data = {"pid": process.pid,
                    "status": process.status(),
                    "percent_cpu_used": process.cpu_percent(interval=0.0),
                    "percent_memory_used": process.memory_percent()}

        except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess):
            data = None

        if data is not None:
            pid_valid[process.name()] = data
    return pid_valid
system_diagnostics_logger.py 文件源码 项目:universe 作者: openai 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def cpu_times(self):
        ''' return {pid: {'user': 0.0, 'sys': 0.0}}, chrome_reset '''
        chrome_procs = self.get_chrome_procs()
        new_pids = {p.pid for p in chrome_procs}
        old_pids = {pid for pid in self.last_cpu_times}
        try:
            cpu_times = {p.pid: p.cpu_times() for p in chrome_procs}
        except psutil.NoSuchProcess:
            # Chrome restarted since fetching the new pids above. Better luck next time.
            return {}, True
        if new_pids != old_pids:
            # We don't know when the Chrome procs were restarted, so don't
            # return elapsed time until next run.
            self.last_cpu_times = cpu_times
            return {}, True
        # Same chrome pids as last run: measure the elapsed cpu times
        ordered_old_times = (self.last_cpu_times[p.pid] for p in chrome_procs)
        ordered_new_times = (cpu_times[p.pid] for p in chrome_procs)
        cpu_times_diff = {p.pid: {'user': (t[0] - l[0]) / self.interval, 'sys': (t[1] - l[1]) / self.interval}
                for (p, t, l) in zip(chrome_procs, ordered_new_times, ordered_old_times)}
        self.last_cpu_times = cpu_times
        return cpu_times_diff, False
handlers.py 文件源码 项目:ransomcare 作者: Happyholic1203 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def on_crypto_ransom(self, evt):
        logger.debug('Whitelist: %s' % json.dumps(self.whitelist, indent=4))
        logger.debug('Suspended: %s' % json.dumps([
            {'pid': p.pid, 'exe': p.exe()} for p in self.suspended
        ], indent=4))
        if any(suspended.pid == evt.pid for suspended in self.suspended):
            return  # ignore captured ransom events

        try:
            p = psutil.Process(evt.pid)
            cmdline = p.cmdline()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            logger.warn('Suspicious process %d exited before being caught'
                        % evt.pid)
            return

        if cmdline not in self.whitelist:
            p.suspend()
            self.suspended.append(p)
            event.EventAskUserAllowOrDeny(p, evt.path).fire()
        else:
            logger.info('Allowed white-listed process: %d' % evt.pid)
sniffers.py 文件源码 项目:ransomcare 作者: Happyholic1203 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_absolute_path(event_raw):
    '''
    Keeps a cache of processes' cwds, in case that their events might come
    after they're terminated.
    '''
    pid = event_raw.get('pid')
    path = event_raw.get('path')
    if path and path[0] == '/':
        return os.path.realpath(path)

    cwd = None
    logger.debug('%r' % pid_cwd)
    try:
        process = psutil.Process(pid)
        cwd = process.cwd()
        pid_cwd[pid] = cwd  # cache every pid's cwd
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        cwd = pid_cwd.get(pid)
        if not cwd:
            return None

    return os.path.realpath(os.path.join(cwd, path))
__init__.py 文件源码 项目:ransomcare 作者: Happyholic1203 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def on_crypto_ransom(self, evt):
        logger.debug('Got crypto ransom event')
        cmdline, exe = None, None
        try:
            p = psutil.Process(evt.pid)
            cmdline = p.cmdline()
            exe = p.exe()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pid_profile = self.engine.pid_profiles.get(evt.pid)
            if pid_profile is not None:
                cmdline = pid_profile.get('cmdline')
                exe = cmdline[0] if cmdline else None
        crypto_ransom_event = {
            'pid': evt.pid,
            'path': evt.path,
            'cmdline': cmdline,
            'exe': exe,
            'timestamp': datetime.datetime.now().isoformat()
        }
        self.web.ctx['events'].append(crypto_ransom_event)
        self.web.socketio.emit('event', crypto_ransom_event)
runner.py 文件源码 项目:distiller 作者: pyoor 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def check(proc, target_name, max_timeout):
    """
    Check CPU usage of target process
    """
    try:
        pid = proc.pid
        start_time = time()
        if psutil.Process(pid).children():
            for child in psutil.Process(pid).children():
                if child.name() == target_name:
                    while True:
                        cpu = all(0 == child.cpu_percent(interval=0.1) for x in xrange(8))
                        if cpu is not None and cpu is True:
                            kill(proc, child.pid)
                            break
                        if max_timeout is not None or max_timeout != 0:
                            end_time = time()
                            elapsed = end_time - start_time
                            if elapsed > max_timeout:
                                kill(proc, child.pid)
                                break
    except psutil.NoSuchProcess:
        pass
isp_data_pollution.py 文件源码 项目:isp-data-pollution 作者: essandess 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def check_phantomjs_process(self):
        """
        Check if phantomjs is running.
        :return: 
        """
        # Check rss and restart if too large, then check existence
        # http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python
        try:
            if not hasattr(self,'driver'): self.open_driver()
            pid, rss_mb = self.phantomjs_pid_and_memory()
            if rss_mb > self.phantomjs_rss_limit_mb:  # memory limit
                self.quit_driver(pid=pid)
                self.open_driver()
                pid, _ = self.phantomjs_pid_and_memory()
            # check existence
            os.kill(pid, 0)
        except (OSError,psutil.NoSuchProcess,Exception) as e:
            if self.debug: print('.phantomjs_pid_and_memory() exception:\n{}'.format(e))
            if issubclass(type(e),psutil.NoSuchProcess):
                raise Exception("There's a phantomjs zombie, and the thread shouldn't have reached this statement.")
            return False
        else:
            return True
isp_data_pollution.py 文件源码 项目:isp-data-pollution 作者: essandess 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def phantomjs_pid_and_memory(self):
        """ Return the pid and memory (MB) of the phantomjs process,
        restart if it's a zombie, and exit if a restart isn't working
        after three attempts. """
        for k in range(3):    # three strikes
            try:
                @self.phantomjs_short_timeout
                def phantomjs_process_pid(): return self.driver.service.process.pid
                pid = phantomjs_process_pid()
                rss_mb = psutil.Process(pid).memory_info().rss / float(2 ** 20)
                break
            except (psutil.NoSuchProcess,Exception) as e:
                if self.debug: print('.service.process.pid exception:\n{}'.format(e))
                self.quit_driver(pid=pid)
                self.open_driver()
        else:  # throw in the towel and exit if no viable phantomjs process after multiple attempts
            print('No viable phantomjs process after multiple attempts!')
            sys.exit(1)
        return (pid, rss_mb)
helpers.py 文件源码 项目:incubator-airflow-old 作者: apache 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def kill_using_shell(logger, pid, signal=signal.SIGTERM):
    try:
        process = psutil.Process(pid)
        # Use sudo only when necessary - consider SubDagOperator and SequentialExecutor case.
        if process.username() != getpass.getuser():
            args = ["sudo", "kill", "-{}".format(int(signal)), str(pid)]
        else:
            args = ["kill", "-{}".format(int(signal)), str(pid)]
        # PID may not exist and return a non-zero error code
        logger.error(subprocess.check_output(args, close_fds=True))
        logger.info("Killed process {} with signal {}".format(pid, signal))
        return True
    except psutil.NoSuchProcess as e:
        logger.warning("Process {} no longer exists".format(pid))
        return False
    except subprocess.CalledProcessError as e:
        logger.warning("Failed to kill process {} with signal {}. Output: {}"
                       .format(pid, signal, e.output))
        return False
system.py 文件源码 项目:psystem 作者: gokhanm 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def pid(self, process_name):
        """
            process_name: System Process Name
            return: Process name's pid, integer
        """
        for proc in psutil.process_iter():
            try:
                pinfo = proc.as_dict(attrs=['pid', 'name'])
                p_name = pinfo['name']
                p_pid = pinfo['pid']

                if process_name == p_name:
                    return p_pid

            except psutil.NoSuchProcess:
                pass
childmgr.py 文件源码 项目:hydra 作者: lake-lerna 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def terminate_process_and_children(self, name):
        """
        Recursively terminate all children of
        respective process
        @args:
        name:   Name of the job
        """
        if name not in self.jobs:
            print("[%s] does not exist as a process!", name)
        ppid = self.jobs[name]['process'].pid
        try:
            parent_proc = psutil.Process(ppid)
        except psutil.NoSuchProcess:
            return
        children = parent_proc.children(recursive=True)
        for proc in children:
            l.debug(proc)
            try:
                proc.send_signal(signal.SIGKILL)
            except:
                pass
test_system.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_process_iter(self):
        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
        sproc = get_test_subprocess()
        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])

        with mock.patch('psutil.Process',
                        side_effect=psutil.NoSuchProcess(os.getpid())):
            self.assertEqual(list(psutil.process_iter()), [])
        with mock.patch('psutil.Process',
                        side_effect=psutil.AccessDenied(os.getpid())):
            with self.assertRaises(psutil.AccessDenied):
                list(psutil.process_iter())
util_test.py 文件源码 项目:certbot 作者: nikoloskii 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_race_condition(self, mock_get_utility, mock_process, mock_net):
        # This tests a race condition, or permission problem, or OS
        # incompatibility in which, for some reason, no process name can be
        # found to match the identified listening PID.
        from psutil._common import sconn
        conns = [
            sconn(fd=-1, family=2, type=1, laddr=("0.0.0.0", 30),
                  raddr=(), status="LISTEN", pid=None),
            sconn(fd=3, family=2, type=1, laddr=("192.168.5.10", 32783),
                  raddr=("20.40.60.80", 22), status="ESTABLISHED", pid=1234),
            sconn(fd=-1, family=10, type=1, laddr=("::1", 54321),
                  raddr=("::1", 111), status="CLOSE_WAIT", pid=None),
            sconn(fd=3, family=2, type=1, laddr=("0.0.0.0", 17),
                  raddr=(), status="LISTEN", pid=4416)]
        mock_net.return_value = conns
        mock_process.side_effect = psutil.NoSuchProcess("No such PID")
        # We simulate being unable to find the process name of PID 4416,
        # which results in returning False.
        self.assertFalse(self._call(17))
        self.assertEqual(mock_get_utility.generic_notification.call_count, 0)
        mock_process.assert_called_once_with(4416)
TorStat.py 文件源码 项目:TorStat 作者: rootlabs 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def TOR_PROC_CHECK():
    isTorRunnin = False
    TOR_INFO = {}
    TOR_PROC = None
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
        except psutil.NoSuchProcess:
            pass
        else:
            if pinfo['name'] == "tor":
                isTorRunnin = True
                TOR_INFO['pid'] = pinfo['pid']
                TOR_INFO['name'] = pinfo['name']
                break

    if isTorRunnin == True:
        print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " Tor is running." + Style.RESET_ALL)
        TOR_PROC = psutil.Process(int(TOR_INFO['pid']))
        return TOR_PROC
    else:
        print ("[" + Fore.RED + Style.BRIGHT + "-" + Style.RESET_ALL + "]" + Fore.RED + Style.BRIGHT + " Tor is not running." + Style.RESET_ALL)
        exit()
ble_communication.py 文件源码 项目:ruuvitag-sensor 作者: ttu 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def stop(hcitool, hcidump):
        # import psutil here so as long as all implementations are in the same file, all will work
        import psutil

        log.info('Stop receiving broadcasts')

        def kill_child_processes(parent_pid):
            try:
                parent = psutil.Process(parent_pid)
            except psutil.NoSuchProcess:
                return

            for process in parent.children(recursive=True):
                subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(process.pid)])

        kill_child_processes(hcitool.pid)
        subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(hcitool.pid)])
        kill_child_processes(hcidump.pid)
        subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(hcidump.pid)])
mService.py 文件源码 项目:mWorkerService 作者: smices 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def status():
    """
    Fetch service status
    :return:
    """
    if master_pid("c") is True:
        print colored(" SERVICE IS RUNNING... ", "white", "on_blue")
        h = PrettyTable([u"??ID", u"????"])
        h.align[u"??ID"] = "l"
        h.align[u"????"] = "l"
        h.padding_width = 1
        pid_list = processors_list("r")
        for pid in pid_list:
            try:
                if psutil.Process(pid).is_running():
                    h.add_row([pid, colored("RUNNING...",attrs=["bold"])])
                else:
                    h.add_row([colored(pid, "magenta", "on_yellow", attrs=["bold"]),
                               colored("STOPED", "magenta", "on_yellow", attrs=["bold"])])
            except psutil.NoSuchProcess:
                h.add_row([colored(pid, "yellow", attrs=["bold", "blink"]),
                           colored("LOSTED", "red", attrs=["bold", "blink"])])
        print h
    else:
        cmsg("SERVICE IS STOPED!", "e")
main.py 文件源码 项目:crondeamon 作者: zhoukunpeng504 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def start():
    old_pid=get_pid()
    try:
        process=psutil.Process(pid=old_pid)
    except psutil.NoSuchProcess as  e :
        process=None
        os.system("rm -rf %s/pid/crondeamon.pid"%datadir)
    if old_pid and process:
        cmd_line=process.cmdline()
        mask=0
        for j in cmd_line:
            if  "twistd" in j  or "crondeamon" in j  :
                mask+=1
        if mask>=2:
            print "server is running ! "
        else:
            os.system("mkdir -p %s/pid"%datadir)
            os.system("mkdir -p %s/log"%datadir)
            os.system("twistd --pidfile %s/pid/crondeamon.pid --logfile %s/log/crondeamon.log crondeamon"%(datadir,datadir))
            print "start success!"
    else:
        os.system("mkdir -p %s/pid"%datadir)
        os.system("mkdir -p %s/log"%datadir)
        os.system("twistd --pidfile %s/pid/crondeamon.pid --logfile %s/log/crondeamon.log crondeamon"%(datadir,datadir))
        print "start success!"
conanserver.py 文件源码 项目:serverthrall 作者: NullSoldier 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def start(self):
        if self.process or self.is_running():
            self.logger.error('Server already running call close_server first')
            return

        if len(self.arguments) == 0:
            self.logger.info('Launching server and waiting for child processes')
        else:
            self.logger.info('Launching server and waiting for child processes with extra arguments, %s' % self.arguments)

        try:
            process = subprocess.Popen([self.path, '-log', self.arguments])
            process = psutil.Process(process.pid)
            self.attach(process)
        except subprocess.CalledProcessError as ex:
            self.logger.exception('Server failed to start... %s' % ex)
            return False
        except psutil.NoSuchProcess as ex:
            self.logger.exception('Server started but crashed shortly after... %s' % ex)
            return False

        self.logger.info('Server running successfully')
        return True
supervisor.py 文件源码 项目:reflector-cluster 作者: lbryio 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def show_prism_info(queues, raw, by_queue, queue_class, worker_class):
    show_queues(queues, raw, by_queue, queue_class, worker_class)
    if not raw:
        click.echo('')
    show_workers(queues, raw, by_queue, queue_class, worker_class)
    show_cluster_info()
    click.echo('')
    click.echo("Redis clients: %i" % len(redis_conn.client_list()))
    click.echo("Local blobs: %i" % len(os.listdir(os.path.expandvars(BLOB_DIR))))

    try:
        click.echo("Open files: %i" % len(server_proc.open_files()))
    except psutil.NoSuchProcess:
        sys.exit(0)
    if not raw:
        click.echo('')
        import datetime
        click.echo('Updated: %s' % datetime.datetime.now())
utils.py 文件源码 项目:ops_tools 作者: juliovp01 项目源码 文件源码 阅读 103 收藏 0 点赞 0 评论 0
def check_process_exists_and_amqp_connected(name):
    processes = filter(lambda p: check_process_name(name, p),
                       psutil.process_iter())
    if not processes:
        critical("%s is not running" % name)
    for p in processes:
        try:
            connections = p.get_connections(kind='inet')
        except psutil.NoSuchProcess:
            continue
        found_amqp = (
            len(list(itertools.takewhile(lambda c: len(c.remote_address) <= 1
                                         or c.remote_address[1]
                                         != AMQP_PORT, connections)))
            != len(connections))
        if found_amqp:
            ok("%s is working." % name)
    critical("%s is not connected to AMQP" % name)
sshd.py 文件源码 项目:idiot 作者: snare 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def run(self):
        with open(os.devnull, 'w') as devnull:
            try:
                # If the service is disabled in Preferences
                # the query returns a non-zero error
                # should use this query better in future
                if subprocess.check_call(['launchctl', 'print', 'system/com.openssh.sshd'], stdout=devnull, stderr=devnull):
                    return (True, "disabled")
                else:
                    return (False, "enabled in Sharing Prefs: Remote Login")
            except subprocess.CalledProcessError as e:
                # this only gets run if sshd isn't enabled by
                # launchd as checked above
                pids = []
                for p in psutil.process_iter():
                    try:
                        if p.name() == 'sshd':
                            pids.append(p.pid)
                    except psutil.NoSuchProcess:
                        pass
                if len(pids):
                    return (False, "enabled manually - see pids: {} ".format(', '.join([str(p) for p in pids])))
                else:
                    return (True, "disabled")


问题


面经


文章

微信
公众号

扫码关注公众号