Assign a single sysctl parameter for this minion

    CLI Example:

    .. code-block:: bash

        salt '*' sysctl.assign net.inet.ip.forwarding 1
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
1035973
function Forwarded(ip, port, secured) {
  this.ip = ip || '127.0.0.1';
  this.secure = !!secured;
  this.port = +port || 0;
}
199943
def cli(env, identifier, no_vs, no_hardware):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', subnet['id']])
    table.add_row(['identifier',
                   '%s/%s' % (subnet['networkIdentifier'],
                              str(subnet['cidr']))])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['network space',
                   utils.lookup(subnet, 'networkVlan', 'networkSpace')])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(['broadcast',
                   subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(['usable ips',
                   subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([vsi['hostname'],
                                  vsi['domain'],
                                  vsi.get('primaryIpAddress'),
                                  vsi.get('primaryBackendIpAddress')])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['hostname', 'domain', 'public_ip', 'private_ip'])
            for hardware in subnet['hardware']:
                hw_table.add_row([hardware['hostname'],
                                  hardware['domain'],
                                  hardware.get('primaryIpAddress'),
                                  hardware.get('primaryBackendIpAddress')])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
930516
def _ip_int_from_prefix(self, prefixlen=None):
        
        if prefixlen is None:
            prefixlen = self._prefixlen
        return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
837092
def cmd(send, msg, args):
    
    if not msg:
        send("Ping what?")
        return
    channel = args['target'] if args['target'] != 'private' else args['nick']
    # CTCP PING
    if "." not in msg and ":" not in msg:
        targets = set(msg.split())
        if len(targets) > 3:
            send("Please specify three or fewer people to ping.")
            return
        for target in targets:
            if not re.match(args['config']['core']['nickregex'], target):
                send("Invalid nick %s" % target)
            else:
                args['handler'].ping_map[target] = channel
                args['handler'].connection.ctcp("PING", target, " ".join(str(time()).split('.')))
        return
    try:
        answer = subprocess.check_output([args['name'], '-W', '1', '-c', '1', msg], stderr=subprocess.STDOUT)
        answer = answer.decode().splitlines()
        send(answer[0])
        send(answer[1])
    except subprocess.CalledProcessError as e:
        if e.returncode == 2:
            send("ping: unknown host " + msg)
        elif e.returncode == 1:
            send(e.output.decode().splitlines()[-2])
689887
def start(self, tcpport=102):
        
        if tcpport != 102:
            logger.info("setting server TCP port to %s" % tcpport)
            self.set_param(snap7.snap7types.LocalPort, tcpport)
        logger.info("starting server on 0.0.0.0:%s" % tcpport)
        return self.library.Srv_Start(self.pointer)
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
1252727
def cli(env, identifier):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)
    global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
                                      name='global ip')

    if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)):
        raise exceptions.CLIAbort('Aborted')

    mgr.cancel_global_ip(global_ip_id)
221947
private NetworkInterface assignNetworkInterfaceTo(
          final DatagramChannel channel,
          final String networkInterfaceName)
  throws IOException {
    
    if (networkInterfaceName != null && !networkInterfaceName.trim().isEmpty()) {
      final NetworkInterface specified = NetworkInterface.getByName(networkInterfaceName);
      if (specified != null) {
        channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, specified);
        return specified;
      }
    }

    // if networkInterfaceName not given or unknown, take best guess
    
    return assignBestGuessNetworkInterfaceTo(channel);
  }
1289917
def add_nat_rule(port, source_interface, dest_interface):
    
    log = logging.getLogger(mod_logger + '.add_nat_rule')
    # Validate args
    if not isinstance(source_interface, basestring):
        msg = 'source_interface argument must be a string'
        log.error(msg)
        raise TypeError(msg)
    if not isinstance(dest_interface, basestring):
        msg = 'dest_interface argument must be a string'
        log.error(msg)
        raise TypeError(msg)

    ip_addresses = ip_addr()
    destination_ip = ip_addresses['eth{i}'.format(i=dest_interface)]
    log.info('Using destination IP address: {d}'.format(d=destination_ip))

    command = ['iptables', '-t', 'nat', '-A', 'PREROUTING', '-i',
               'eth{s}'.format(s=source_interface), '-p', 'tcp',
               '--dport', str(port), '-j', 'DNAT', '--to',
               '{d}:{p}'.format(p=port, d=destination_ip)]
    log.info('Running command: {c}'.format(c=command))
    try:
        subprocess.check_call(command)
    except OSError:
        _, ex, trace = sys.exc_info()
        msg = 'There was a problem running command: {c}\n{e}'.format(c=command, e=str(ex))
        log.error(msg)
        raise OSError, msg, trace
    except subprocess.CalledProcessError:
        _, ex, trace = sys.exc_info()
        msg = 'Command returned a non-zero exit code: {c}\n{e}'.format(c=command, e=str(ex))
        log.error(msg)
        raise OSError, msg, trace
    else:
        log.info('Successfully ran command: {c}'.format(c=command))

    # Save the iptables with the new NAT rule
    try:
        save_iptables()
    except OSError:
        _, ex, trace = sys.exc_info()
        msg = 'OSError: There was a problem saving iptables rules\n{e}'.format(e=str(ex))
        raise OSError, msg, trace
    log.info('Successfully saved iptables rules with the NAT rule')
557955
def inet_ntop(address_family, packed_ip):
    
    global __inet_ntop
    if __inet_ntop is None:
        if hasattr(socket, 'inet_ntop'):
            __inet_ntop = socket.inet_ntop
        else:
            from ospd import win_socket
            __inet_ntop = win_socket.inet_ntop

    return __inet_ntop(address_family, packed_ip)
84564
def setup_link(self, interface, cidr):
        
        # clear old ipaddr in interface
        cmd = ['ip', 'addr', 'flush', 'dev', interface]
        agent_utils.execute(cmd, root=True)
        ip = IPNetwork(cidr)
        cmd = ['ip', 'addr', 'add', cidr, 'broadcast',
               str(ip.broadcast), 'dev', interface]
        stdcode, stdout = agent_utils.execute(cmd, root=True)
        if stdcode == 0:
            cmd = ['ip', 'link', 'set', 'dev', interface, 'up']
            stdcode, stdout = agent_utils.execute(cmd, root=True)
            if stdcode == 0:
                return agent_utils.make_response(code=stdcode)
        # execute failed.
        message = stdout.pop(0)
        return agent_utils.make_response(code=stdcode, message=message)
1310363
def _ioctl (self, func, args):
        """"""
        import fcntl
        return fcntl.ioctl(self.sockfd.fileno(), func, args)
659820
def _set_init_system(self, client):
        """"""
        if not self.init_system:
            try:
                out = ipa_utils.execute_ssh_command(
                    client,
                    'ps -p 1 -o comm='
                )
            except Exception as e:
                raise IpaDistroException(
                    'An error occurred while retrieving'
                    ' the distro init system: %s' % e
                )
            if out:
                self.init_system = out.strip()
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
1297095
def inet_to_str(inet):
    
    # First try ipv4 and then ipv6
    try:
        return socket.inet_ntop(socket.AF_INET, inet)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, inet)
313682
def in_subnet(cidr, addr=None):
    '''
    
    '''
    try:
        cidr = ipaddress.ip_network(cidr)
    except ValueError:
        log.error('Invalid CIDR \'%s\'', cidr)
        return False

    if addr is None:
        addr = ip_addrs()
        addr.extend(ip_addrs6())
    elif not isinstance(addr, (list, tuple)):
        addr = (addr,)

    return any(ipaddress.ip_address(item) in cidr for item in addr)