Beispiel #1
0
 def find_orphans(self, cmdline):
     '''Find orphaned processes matching the specified cmdline'''
     ret = []
     if six.PY3:
         cmdline = ' '.join(cmdline)
         for proc in psutils.process_iter():
             try:
                 for item in proc.cmdline():
                     if cmdline in item:
                         ret.append(proc)
             except psutils.NoSuchProcess:
                 # Process exited between when process_iter was invoked and
                 # when we tried to invoke this instance's cmdline() func.
                 continue
     else:
         cmd_len = len(cmdline)
         for proc in psutils.process_iter():
             try:
                 proc_cmdline = proc.cmdline()
             except psutils.NoSuchProcess:
                 # Process exited between when process_iter was invoked and
                 # when we tried to invoke this instance's cmdline() func.
                 continue
             if any((cmdline == proc_cmdline[n:n + cmd_len])
                    for n in range(len(proc_cmdline) - cmd_len + 1)):
                 ret.append(proc)
     return ret
Beispiel #2
0
 def find_orphans(self, cmdline):
     """Find orphaned processes matching the specified cmdline"""
     ret = []
     if six.PY3:
         cmdline = " ".join(cmdline)
         for proc in psutils.process_iter():
             try:
                 for item in proc.cmdline():
                     if cmdline in item:
                         ret.append(proc)
             except psutils.NoSuchProcess:
                 # Process exited between when process_iter was invoked and
                 # when we tried to invoke this instance's cmdline() func.
                 continue
             except psutils.AccessDenied:
                 # We might get access denied if not running as root
                 if not salt.utils.platform.is_windows():
                     pinfo = proc.as_dict(attrs=["pid", "name", "username"])
                     log.error(
                         "Unable to access process %s, "
                         "running command %s as user %s",
                         pinfo["pid"],
                         pinfo["name"],
                         pinfo["username"],
                     )
                     continue
     else:
         cmd_len = len(cmdline)
         for proc in psutils.process_iter():
             try:
                 proc_cmdline = proc.cmdline()
             except psutils.NoSuchProcess:
                 # Process exited between when process_iter was invoked and
                 # when we tried to invoke this instance's cmdline() func.
                 continue
             except psutils.AccessDenied:
                 # We might get access denied if not running as root
                 if not salt.utils.platform.is_windows():
                     pinfo = proc.as_dict(attrs=["pid", "name", "username"])
                     log.error(
                         "Unable to access process %s, "
                         "running command %s as user %s",
                         pinfo["pid"],
                         pinfo["name"],
                         pinfo["username"],
                     )
                     continue
             if any((cmdline == proc_cmdline[n:n + cmd_len])
                    for n in range(len(proc_cmdline) - cmd_len + 1)):
                 ret.append(proc)
     return ret
Beispiel #3
0
 def find_orphans(self, cmdline):
     '''Find orphaned processes matching the specified cmdline'''
     ret = []
     if six.PY3:
         cmdline = ' '.join(cmdline)
         for proc in psutils.process_iter():
             for item in proc.cmdline():
                 if cmdline in item:
                     ret.append(proc)
     else:
         cmd_len = len(cmdline)
         for proc in psutils.process_iter():
             proc_cmdline = proc.cmdline()
             if any((cmdline == proc_cmdline[n:n + cmd_len])
                     for n in range(len(proc_cmdline) - cmd_len + 1)):
                 ret.append(proc)
     return ret
Beispiel #4
0
def pkill(pattern, user=None, signal=15, full=False):
    """
    Kill processes matching a pattern.

    .. code-block:: bash

        salt '*' ps.pkill pattern [user=username] [signal=signal_number] \\
                [full=(true|false)]

    pattern
        Pattern to search for in the process list.

    user
        Limit matches to the given username. Default: All users.

    signal
        Signal to send to the process(es). See manpage entry for kill
        for possible values. Default: 15 (SIGTERM).

    full
        A boolean value indicating whether only the name of the command or
        the full command line should be matched against the pattern.

    **Examples:**

    Send SIGHUP to all httpd processes on all 'www' minions:

    .. code-block:: bash

        salt 'www.*' ps.pkill httpd signal=1

    Send SIGKILL to all bash processes owned by user 'tom':

    .. code-block:: bash

        salt '*' ps.pkill bash signal=9 user=tom
    """

    killed = []
    for proc in psutil.process_iter():
        name_match = (
            pattern in " ".join(_get_proc_cmdline(proc))
            if full
            else pattern in _get_proc_name(proc)
        )
        user_match = True if user is None else user == _get_proc_username(proc)
        if name_match and user_match:
            try:
                proc.send_signal(signal)
                killed.append(_get_proc_pid(proc))
            except psutil.NoSuchProcess:
                pass
    if not killed:
        return None
    else:
        return {"killed": killed}
Beispiel #5
0
def pkill(pattern, user=None, signal=15, full=False):
    '''
    Kill processes matching a pattern.

    .. code-block:: bash

        salt '*' ps.pkill pattern [user=username] [signal=signal_number] \\
                [full=(true|false)]

    pattern
        Pattern to search for in the process list.

    user
        Limit matches to the given username. Default: All users.

    signal
        Signal to send to the process(es). See manpage entry for kill
        for possible values. Default: 15 (SIGTERM).

    full
        A boolean value indicating whether only the name of the command or
        the full command line should be matched against the pattern.

    **Examples:**

    Send SIGHUP to all httpd processes on all 'www' minions:

    .. code-block:: bash

        salt 'www.*' ps.pkill httpd signal=1

    Send SIGKILL to all bash processes owned by user 'tom':

    .. code-block:: bash

        salt '*' ps.pkill bash signal=9 user=tom
    '''

    killed = []
    for proc in psutil.process_iter():
        name_match = pattern in ' '.join(_get_proc_cmdline(proc)) if full \
            else pattern in _get_proc_name(proc)
        user_match = True if user is None else user == _get_proc_username(proc)
        if name_match and user_match:
            try:
                proc.send_signal(signal)
                killed.append(_get_proc_pid(proc))
            except psutil.NoSuchProcess:
                pass
    if not killed:
        return None
    else:
        return {'killed': killed}
Beispiel #6
0
def beacon(config):
    """
    Scan for processes and fire events

    Example Config

    .. code-block:: yaml

        beacons:
          ps:
            - processes:
                salt-master: running
                mysql: stopped

    The config above sets up beacons to check that
    processes are running or stopped.
    """
    ret = []
    procs = []
    for proc in psutil.process_iter():
        try:
            _name = proc.name()
        except psutil.NoSuchProcess:
            # The process is now gone
            continue
        if _name not in procs:
            procs.append(_name)

    _config = {}
    list(map(_config.update, config))

    for process in _config.get("processes", {}):
        ret_dict = {}
        if _config["processes"][process] == "running":
            if process in procs:
                ret_dict[process] = "Running"
                ret.append(ret_dict)
        elif _config["processes"][process] == "stopped":
            if process not in procs:
                ret_dict[process] = "Stopped"
                ret.append(ret_dict)
        else:
            if process not in procs:
                ret_dict[process] = False
                ret.append(ret_dict)
    return ret
Beispiel #7
0
def pgrep(pattern, user=None, full=False):
    '''
    Return the pids for processes matching a pattern.

    If full is true, the full command line is searched for a match,
    otherwise only the name of the command is searched.

    .. code-block:: bash

        salt '*' ps.pgrep pattern [user=username] [full=(true|false)]

    pattern
        Pattern to search for in the process list.

    user
        Limit matches to the given username. Default: All users.

    full
        A boolean value indicating whether only the name of the command or
        the full command line should be matched against the pattern.

    **Examples:**

    Find all httpd processes on all 'www' minions:

    .. code-block:: bash

        salt 'www.*' ps.pgrep httpd

    Find all bash processes owned by user 'tom':

    .. code-block:: bash

        salt '*' ps.pgrep bash user=tom
    '''

    procs = []
    for proc in psutil.process_iter():
        name_match = pattern in ' '.join(_get_proc_cmdline(proc)) if full \
            else pattern in _get_proc_name(proc)
        user_match = True if user is None else user == _get_proc_username(proc)
        if name_match and user_match:
            procs.append(_get_proc_pid(proc))
    return procs or None
Beispiel #8
0
def pgrep(pattern, user=None, full=False):
    '''
    Return the pids for processes matching a pattern.

    If full is true, the full command line is searched for a match,
    otherwise only the name of the command is searched.

    .. code-block:: bash

        salt '*' ps.pgrep pattern [user=username] [full=(true|false)]

    pattern
        Pattern to search for in the process list.

    user
        Limit matches to the given username. Default: All users.

    full
        A boolean value indicating whether only the name of the command or
        the full command line should be matched against the pattern.

    **Examples:**

    Find all httpd processes on all 'www' minions:

    .. code-block:: bash

        salt 'www.*' ps.pgrep httpd

    Find all bash processes owned by user 'tom':

    .. code-block:: bash

        salt '*' ps.pgrep bash user=tom
    '''

    procs = []
    for proc in psutil.process_iter():
        name_match = pattern in ' '.join(_get_proc_cmdline(proc)) if full \
            else pattern in _get_proc_name(proc)
        user_match = True if user is None else user == _get_proc_username(proc)
        if name_match and user_match:
            procs.append(_get_proc_pid(proc))
    return procs or None
Beispiel #9
0
def beacon(config):
    '''
    Scan for processes and fire events

    Example Config

    .. code-block:: yaml

        beacons:
          ps:
            - processes:
                salt-master: running
                mysql: stopped

    The config above sets up beacons to check that
    processes are running or stopped.
    '''
    ret = []
    procs = []
    for proc in psutil.process_iter():
        _name = proc.name()
        if _name not in procs:
            procs.append(_name)

    _config = {}
    list(map(_config.update, config))

    for process in _config.get('processes', {}):
        ret_dict = {}
        if _config['processes'][process] == 'running':
            if process in procs:
                ret_dict[process] = 'Running'
                ret.append(ret_dict)
        elif _config['processes'][process] == 'stopped':
            if process not in procs:
                ret_dict[process] = 'Stopped'
                ret.append(ret_dict)
        else:
            if process not in procs:
                ret_dict[process] = False
                ret.append(ret_dict)
    return ret
Beispiel #10
0
def beacon(config):
    '''
    Scan for processes and fire events with all process data

    Example Config

    .. code-block:: yaml

        beacons:
          allproc: []
    '''
    ret = []
    procs = set()
    for proc in psutil.process_iter():
        _name = proc.name()
        if _name.startswith('[') and _name.endswith(']'):
            continue
        procs.add(_name)
    for name in procs:
        ret.append({'name': name})
    return ret
Beispiel #11
0
def beacon(config):
    '''
    Scan for processes and fire events

    Example Config

    .. code-block:: yaml

        beacons:
          ps:
            salt-master: running
            mysql: stopped

    The config above sets up beacons to check that
    processes are running or stopped.
    '''
    ret = []
    procs = []
    for proc in psutil.process_iter():
        _name = proc.name()
        if _name not in procs:
            procs.append(_name)

    for entry in config:
        for process in entry:
            ret_dict = {}
            if entry[process] == 'running':
                if process not in procs:
                    ret_dict[process] = 'Stopped'
                    ret.append(ret_dict)
            elif entry[process] == 'stopped':
                if process in procs:
                    ret_dict[process] = 'Running'
                    ret.append(ret_dict)
            else:
                if process not in procs:
                    ret_dict[process] = False
                    ret.append(ret_dict)
    return ret
Beispiel #12
0
def beacon(config):
    '''
    Scan for processes and fire events with all process data

    Example Config

    .. code-block:: yaml

        beacons:
          allproc: []
    '''
    ret = []
    procs = set()
    for proc in psutil.process_iter():
        name = proc.name()
        # These rotating kworkers polute the dataset
        if name.startswith('kworker/'):
            continue
        procs.add(name)
    for name in procs:
        ret.append({'name': name})
    return ret
Beispiel #13
0
Datei: ps.py Projekt: bryson/salt
def beacon(config):
    '''
    Scan for processes and fire events

    Example Config

    .. code-block:: yaml

        beacons:
          ps:
            salt-master: running
            mysql: stopped

    The config above sets up beacons to check that
    processes are running or stopped.
    '''
    ret = []
    procs = []
    for proc in psutil.process_iter():
        _name = proc.name()
        if _name not in procs:
            procs.append(_name)

    for process in config:
        ret_dict = {}
        if config[process] == 'running':
            if process not in procs:
                ret_dict[process] = 'Stopped'
                ret.append(ret_dict)
        elif config[process] == 'stopped':
            if process in procs:
                ret_dict[process] = 'Running'
                ret.append(ret_dict)
        else:
            if process not in procs:
                ret_dict[process] = False
                ret.append(ret_dict)
    return ret
Beispiel #14
0
 def find_orphans(self, cmdline):
     '''Find orphaned processes matching the specified cmdline'''
     return [
         x for x in psutils.process_iter()
         if x.ppid() == 1 and x.cmdline()[-len(cmdline):] == cmdline
     ]
Beispiel #15
0
def pgrep(pattern, user=None, full=False, pattern_is_regex=False):
    '''
    Return the pids for processes matching a pattern.

    If full is true, the full command line is searched for a match,
    otherwise only the name of the command is searched.

    .. code-block:: bash

        salt '*' ps.pgrep pattern [user=username] [full=(true|false)]

    pattern
        Pattern to search for in the process list.

    user
        Limit matches to the given username. Default: All users.

    full
        A boolean value indicating whether only the name of the command or
        the full command line should be matched against the pattern.

    pattern_is_regex
        This flag enables ps.pgrep to mirror the regex search functionality
         found in the pgrep command line utility.

        .. versionadded:: Neon

    **Examples:**

    Find all httpd processes on all 'www' minions:

    .. code-block:: bash

        salt 'www.*' ps.pgrep httpd

    Find all bash processes owned by user 'tom':

    .. code-block:: bash

        salt '*' ps.pgrep bash user=tom
    '''
    procs = []

    if pattern_is_regex:
        pattern = re.compile(str(pattern))

    procs = []
    for proc in psutil.process_iter():
        if full:
            process_line = ' '.join(_get_proc_cmdline(proc))
        else:
            process_line = _get_proc_name(proc)

        if pattern_is_regex:
            name_match = re.search(pattern, process_line)
        else:
            name_match = pattern in process_line

        user_match = True if user is None else user == _get_proc_username(proc)

        if name_match and user_match:
            procs.append(_get_proc_pid(proc))

    return procs or None