Assign and persist a simple sysctl parameter for this minion

    CLI Example:

    .. code-block:: bash

        salt '*' sysctl.persist net.inet.icmp.icmplim 50
978882
def persist(name, value, config='/etc/sysctl.conf'):
    '''
    
    '''
    nlines = []
    edited = False
    value = six.text_type(value)

    # create /etc/sysctl.conf if not present
    if not os.path.isfile(config):
        try:
            with salt.utils.files.fopen(config, 'w+'):
                pass
        except (IOError, OSError):
            msg = 'Could not create {0}'
            raise CommandExecutionError(msg.format(config))

    with salt.utils.files.fopen(config, 'r') as ifile:
        for line in ifile:
            line = salt.utils.stringutils.to_unicode(line)
            m = re.match(r'{0}(\??=)'.format(name), line)
            if not m:
                nlines.append(line)
                continue
            else:
                key, rest = line.split('=', 1)
                if rest.startswith('"'):
                    _, rest_v, rest = rest.split('"', 2)
                elif rest.startswith('\''):
                    _, rest_v, rest = rest.split('\'', 2)
                else:
                    rest_v = rest.split()[0]
                    rest = rest[len(rest_v):]
                if rest_v == value:
                    return 'Already set'
                new_line = '{0}{1}{2}{3}'.format(name, m.group(1), value, rest)
                nlines.append(new_line)
                edited = True

    if not edited:
        newline = '{0}={1}'.format(name, value)
        nlines.append("{0}\n".format(newline))

    with salt.utils.files.fopen(config, 'wb') as ofile:
        ofile.writelines(
            salt.utils.data.encode(nlines)
        )

    assign(name, value)

    return 'Updated'
278210
def symput(self, name, value):
        
        ll = self.submit("%let " + name + "=%NRBQUOTE(" + str(value) + ");\n")
161207
def set_special(user,
                special,
                cmd,
                commented=False,
                comment=None,
                identifier=None):
    '''
    
    '''
    lst = list_tab(user)
    for cron in lst['special']:
        cid = _cron_id(cron)
        if _cron_matched(cron, cmd, identifier):
            test_setted_id = (
                cron['identifier'] is None
                and SALT_CRON_NO_IDENTIFIER
                or cron['identifier'])
            tests = [(cron['comment'], comment),
                     (cron['commented'], commented),
                     (identifier, test_setted_id),
                     (cron['spec'], special)]
            if cid or identifier:
                tests.append((cron['cmd'], cmd))
            if any([_needs_change(x, y) for x, y in tests]):
                rm_special(user, cmd, identifier=cid)

                # Use old values when setting the new job if there was no
                # change needed for a given parameter
                if not _needs_change(cron['spec'], special):
                    special = cron['spec']
                if not _needs_change(cron['commented'], commented):
                    commented = cron['commented']
                if not _needs_change(cron['comment'], comment):
                    comment = cron['comment']
                if not _needs_change(cron['cmd'], cmd):
                    cmd = cron['cmd']
                    if (
                        cid == SALT_CRON_NO_IDENTIFIER
                    ):
                        if identifier:
                            cid = identifier
                        if (
                            cid == SALT_CRON_NO_IDENTIFIER
                            and cron['identifier'] is None
                        ):
                            cid = None
                        cron['identifier'] = cid
                if not cid or (
                    cid and not _needs_change(cid, identifier)
                ):
                    identifier = cid
                jret = set_special(user, special, cmd, commented=commented,
                                   comment=comment, identifier=identifier)
                if jret == 'new':
                    return 'updated'
                else:
                    return jret
            return 'present'
    cron = {'spec': special,
            'cmd': cmd,
            'identifier': identifier,
            'comment': comment,
            'commented': commented}
    lst['special'].append(cron)

    comdat = _write_cron_lines(user, _render_tab(lst))
    if comdat['retcode']:
        # Failed to commit, return the error
        return comdat['stderr']
    return 'new'
1335053
def set_cmd(name, accepts_value=False):
    
    def decorator(func):
        SET_COMMANDS[name] = func
        if accepts_value:
            SET_COMMANDS_TAKING_VALUE.add(name)
        return func
    return decorator
1062890
function persist(pErr, pVal) {
          if (pErr) {
            return cb(pErr);
          }

          if (ttl) {
            conn.setex(key, ttl, pVal, handleResponse(conn, cb));
          } else {
            conn.set(key, pVal, handleResponse(conn, cb));
          }
        }
1355533
def send_sysex(self, sysex_cmd, data):
        
        msg = bytearray([START_SYSEX, sysex_cmd])
        msg.extend(data)
        msg.append(END_SYSEX)
        self.sp.write(msg)
651040
def set_present(name, set_type, family='ipv4', **kwargs):
    '''
    
    '''

    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    set_check = __salt__['ipset.check_set'](name)
    if set_check is True:
        ret['result'] = True
        ret['comment'] = ('ipset set {0} already exists for {1}'
                          .format(name, family))
        return ret

    if __opts__['test']:
        ret['comment'] = 'ipset set {0} would be added for {1}'.format(
            name,
            family)
        return ret
    command = __salt__['ipset.new_set'](name, set_type, family, **kwargs)
    if command is True:
        ret['changes'] = {'locale': name}
        ret['result'] = True
        ret['comment'] = ('ipset set {0} created successfully for {1}'
                          .format(name, family))
        return ret
    else:
        ret['result'] = False
        ret['comment'] = 'Failed to create set {0} for {2}: {1}'.format(
            name,
            command.strip(),
            family
        )
        return ret
647459
def _ctl_cmd(cmd, name, conf_file, bin_env):
    '''
    
    '''
    ret = [_get_supervisorctl_bin(bin_env)]
    if conf_file is not None:
        ret += ['-c', conf_file]
    ret.append(cmd)
    if name:
        ret.append(name)
    return ret
145094
def _set_syslog_config_helper(host, username, password, syslog_config, config_value,
                              protocol=None, port=None, reset_service=None, esxi_host=None, credstore=None):
    '''
    
    '''
    cmd = 'system syslog config set --{0} {1}'.format(syslog_config, config_value)
    ret_dict = {}

    valid_resets = ['logdir', 'loghost', 'default-rotate',
                    'default-size', 'default-timeout', 'logdir-unique']
    if syslog_config not in valid_resets:
        ret_dict.update({'success': False,
                         'message': '\'{0}\' is not a valid config variable.'.format(syslog_config)})
        return ret_dict

    response = salt.utils.vmware.esxcli(host, username, password, cmd,
                                        protocol=protocol, port=port,
                                        esxi_host=esxi_host, credstore=credstore)

    # Update the return dictionary for success or error messages.
    if response['retcode'] != 0:
        ret_dict.update({syslog_config: {'success': False,
                                         'message': response['stdout']}})
    else:
        ret_dict.update({syslog_config: {'success': True}})

    # Restart syslog for each host, if desired.
    if reset_service:
        if esxi_host:
            host_name = esxi_host
            esxi_host = [esxi_host]
        else:
            host_name = host
        response = syslog_service_reload(host, username, password,
                                         protocol=protocol, port=port,
                                         esxi_hosts=esxi_host, credstore=credstore).get(host_name)
        ret_dict.update({'syslog_restart': {'success': response['retcode'] == 0}})

    return ret_dict
141512
def sysctl():
    '''
    
    '''
    ret = {}
    sysctl_jail = __salt__['cmd.run']('sysctl security.jail')
    for line in sysctl_jail.splitlines():
        key, value = line.split(':', 1)
        ret[key.strip()] = value.strip()
    return ret
745282
def assign(name, value):
    '''
    
    '''
    value = six.text_type(value)

    if six.PY3:
        tran_tab = name.translate(''.maketrans('./', '/.'))
    else:
        if isinstance(name, unicode):  # pylint: disable=incompatible-py3-code,undefined-variable
            trans_args = {ord('/'): u'.', ord('.'): u'/'}
        else:
            trans_args = string.maketrans('./', '/.')
        tran_tab = name.translate(trans_args)

    sysctl_file = '/proc/sys/{0}'.format(tran_tab)
    if not os.path.exists(sysctl_file):
        raise CommandExecutionError('sysctl {0} does not exist'.format(name))

    ret = {}
    cmd = 'sysctl -w {0}="{1}"'.format(name, value)
    data = __salt__['cmd.run_all'](cmd, python_shell=False)
    out = data['stdout']
    err = data['stderr']

    # Example:
    #    # sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
    #    net.ipv4.tcp_rmem = 4096 87380 16777216
    regex = re.compile(r'^{0}\s+=\s+{1}$'.format(re.escape(name), re.escape(value)))

    if not regex.match(out) or 'Invalid argument' in six.text_type(err):
        if data['retcode'] != 0 and err:
            error = err
        else:
            error = out
        raise CommandExecutionError('sysctl -w failed: {0}'.format(error))
    new_name, new_value = out.split(' = ', 1)
    ret[new_name] = new_value
    return ret
1085958
def cli(server,port,client):
    
    tn = telnetlib.Telnet(host=server,port=port)
    tn.write('kill %s\n'%client.encode('utf-8'))
    tn.write('exit\n')
    os._exit(0)
435185
def _persist(self):
        
        # run the block/command
        for command in self.commands:
            try:
                process = Popen(
                    [command],
                    stdout=PIPE,
                    stderr=PIPE,
                    universal_newlines=True,
                    env=self.env,
                    shell=True,
                )
            except Exception as e:
                retcode = process.poll()
                msg = "Command '{cmd}' {error} retcode {retcode}"
                self.py3.log(msg.format(cmd=command, error=e, retcode=retcode))

            # persistent blocklet output can be of two forms.  Either each row
            # of the output is on a new line this is much easier to deal with)
            # or else the output can be continuous and just flushed when ready.
            # The second form is more tricky, if we find newlines then we
            # switch to easy parsing of the output.

            # When we have output we store in self.persistent_output and then
            # trigger the module to update.

            fd = process.stdout.fileno()
            fl = fcntl.fcntl(fd, fcntl.F_GETFL)
            has_newlines = False
            while True:
                line = process.stdout.read(1)
                # switch to a non-blocking read as we do not know the output
                # length
                fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
                line += process.stdout.read(1024)
                # switch back to blocking so we can wait for the next output
                fcntl.fcntl(fd, fcntl.F_SETFL, fl)
                if process.poll():
                    break
                if self.py3.is_python_2():
                    line = line.decode("utf-8")
                self.persistent_output = line
                self.py3.update()
                if line[-1] == "\n":
                    has_newlines = True
                    break
                if line == "":
                    break
            if has_newlines:
                msg = "Switch to newline persist method {cmd}"
                self.py3.log(msg.format(cmd=command))
                # just read the output in a sane manner
                for line in iter(process.stdout.readline, b""):
                    if process.poll():
                        break
                    if self.py3.is_python_2():
                        line = line.decode("utf-8")
                    self.persistent_output = line
                    self.py3.update()
        self.py3.log("command exited {cmd}".format(cmd=command))
        self.persistent_output = "Error\nError\n{}".format(
            self.py3.COLOR_ERROR or self.py3.COLOR_BAD
        )
        self.py3.update()
1011441
def set_(device, **kwargs):
    '''
    
    '''
    empty = {'block-soft-limit': 0, 'block-hard-limit': 0,
             'file-soft-limit': 0, 'file-hard-limit': 0}

    current = None
    cmd = 'setquota'
    if 'user' in kwargs:
        cmd += ' -u {0} '.format(kwargs['user'])
        parsed = _parse_quota(device, '-u')
        if kwargs['user'] in parsed:
            current = parsed['Users'][kwargs['user']]
        else:
            current = empty
        ret = 'User: {0}'.format(kwargs['user'])

    if 'group' in kwargs:
        if 'user' in kwargs:
            raise SaltInvocationError(
                'Please specify a user or group, not both.'
            )
        cmd += ' -g {0} '.format(kwargs['group'])
        parsed = _parse_quota(device, '-g')
        if kwargs['group'] in parsed:
            current = parsed['Groups'][kwargs['group']]
        else:
            current = empty
        ret = 'Group: {0}'.format(kwargs['group'])

    if not current:
        raise CommandExecutionError('A valid user or group was not found')

    for limit in ('block-soft-limit', 'block-hard-limit',
                  'file-soft-limit', 'file-hard-limit'):
        if limit in kwargs:
            current[limit] = kwargs[limit]

    cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'],
                                        current['block-hard-limit'],
                                        current['file-soft-limit'],
                                        current['file-hard-limit'],
                                        device)

    result = __salt__['cmd.run_all'](cmd, python_shell=False)
    if result['retcode'] != 0:
        raise CommandExecutionError(
            'Unable to set desired quota. Error follows: \n{0}'
            .format(result['stderr'])
        )
    return {ret: current}
773118
def assign(name, value):
    '''
    
    '''
    ret = {}
    cmd = 'sysctl {0}="{1}"'.format(name, value)
    data = __salt__['cmd.run_all'](cmd)

    # Certain values cannot be set from this console, at the current
    # securelevel or there are other restrictions that prevent us
    # from applying the setting rightaway.
    if re.match(r'^sysctl:.*: Operation not permitted$', data['stderr']) or \
      data['retcode'] != 0:
        raise CommandExecutionError('sysctl failed: {0}'.format(
            data['stderr']))
    new_name, new_value = data['stdout'].split(':', 1)
    ret[new_name] = new_value.split(' -> ')[-1]
    return ret
1071604
def set_(name, value, **kwargs):
    '''
    
    '''

    cmd = 'sysrc -v'

    if 'file' in kwargs:
        cmd += ' -f '+kwargs['file']

    if 'jail' in kwargs:
        cmd += ' -j '+kwargs['jail']

    # This is here because the YAML parser likes to convert the string literals
    # YES, NO, Yes, No, True, False, etc. to boolean types.  However, in this case,
    # we will check to see if that happened and replace it with "YES" or "NO" because
    # those items are accepted in sysrc.
    if type(value) == bool:
        if value:
            value = "YES"
        else:
            value = "NO"

    # This is here for the same reason, except for numbers
    if type(value) == int:
        value = str(value)

    cmd += ' '+name+"=\""+value+"\""

    sysrcs = __salt__['cmd.run'](cmd)

    ret = {}
    for sysrc in sysrcs.split("\n"):
        rcfile = sysrc.split(': ')[0]
        var = sysrc.split(': ')[1]
        oldval = sysrc.split(': ')[2].strip().split("->")[0]
        newval = sysrc.split(': ')[2].strip().split("->")[1]
        if rcfile not in ret:
            ret[rcfile] = {}
        ret[rcfile][var] = newval
    return ret
943845
public void setPersistentTimestamp(long newTimestamp) throws FatalChronosException,
      ChronosException {
    if (newTimestamp <= persistentTimestamp) {
      throw new FatalChronosException("Fatal error to set a smaller timestamp");
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("Setting persistent timestamp " + newTimestamp + " in ZooKeeper");
    }

    for (int i = 0; i <= connectRetryTimes; ++i) {
      try {
        ZooKeeperUtil.setData(this, persistentTimestampZnode, ZooKeeperUtil.longToBytes(newTimestamp));
        persistentTimestamp = newTimestamp;
        break;
      } catch (KeeperException e) {
        if (i == connectRetryTimes) {
          throw new ChronosException(
              "Error to set persistent timestamp in ZooKeeper after retrying", e);
        }
        LOG.info("Exception to set persistent timestamp in ZooKeeper, retry " + (i + 1) + " times");
      }
    }
  }