INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the formatted outputter string removing the ANSI escape sequences.
def string_format(data, out, opts=None, **kwargs): ''' Return the formatted outputter string, removing the ANSI escape sequences. ''' raw_output = try_printout(data, out, opts, **kwargs) ansi_escape = re.compile(r'\x1b[^m]*m') return ansi_escape.sub('', raw_output)
Return the formatted string as HTML.
def html_format(data, out, opts=None, **kwargs): ''' Return the formatted string as HTML. ''' ansi_escaped_string = string_format(data, out, opts, **kwargs) return ansi_escaped_string.replace(' ', '&nbsp;').replace('\n', '<br />')
Replace ESC ( ASCII 27/ Oct 33 ) to prevent unsafe strings from writing their own terminal manipulation commands
def strip_esc_sequence(txt): ''' Replace ESC (ASCII 27/Oct 33) to prevent unsafe strings from writing their own terminal manipulation commands ''' if isinstance(txt, six.string_types): try: return txt.replace('\033', '?') except UnicodeDecodeError: return txt....
Split out a domain in its parents
def _tree(domain, tld=False): ''' Split out a domain in its parents Leverages tldextract to take the TLDs from publicsuffix.org or makes a valiant approximation of that :param domain: dc2.ams2.example.com :param tld: Include TLD in list :return: [ 'dc2.ams2.example.com', 'ams2.example.com'...
schema = OrderedDict ( { prio: int weight: int port: to_port name: str } ) rec_data = 10 20 25 myawesome. nl
def _data2rec(schema, rec_data): ''' schema = OrderedDict({ 'prio': int, 'weight': int, 'port': to_port, 'name': str, }) rec_data = '10 20 25 myawesome.nl' res = {'prio': 10, 'weight': 20, 'port': 25 'name': 'myawesome.nl'} ''' try: rec_fields = rec_d...
Use dig to lookup addresses: param name: Name of record to search: param rdtype: DNS record type: param timeout: server response timeout: param servers: [] of servers to use: return: [] of records or False if error
def _lookup_dig(name, rdtype, timeout=None, servers=None, secure=None): ''' Use dig to lookup addresses :param name: Name of record to search :param rdtype: DNS record type :param timeout: server response timeout :param servers: [] of servers to use :return: [] of records or False if error ...
Use drill to lookup addresses: param name: Name of record to search: param rdtype: DNS record type: param timeout: command return timeout: param servers: [] of servers to use: return: [] of records or False if error
def _lookup_drill(name, rdtype, timeout=None, servers=None, secure=None): ''' Use drill to lookup addresses :param name: Name of record to search :param rdtype: DNS record type :param timeout: command return timeout :param servers: [] of servers to use :return: [] of records or False if erro...
Use Python s socket interface to lookup addresses: param name: Name of record to search: param rdtype: A or AAAA: param timeout: ignored: return: [] of addresses or False if error
def _lookup_gai(name, rdtype, timeout=None): ''' Use Python's socket interface to lookup addresses :param name: Name of record to search :param rdtype: A or AAAA :param timeout: ignored :return: [] of addresses or False if error ''' try: sock_t = { 'A': socket.AF_I...
Use host to lookup addresses: param name: Name of record to search: param server: Server to query: param rdtype: DNS record type: param timeout: server response wait: return: [] of records or False if error
def _lookup_host(name, rdtype, timeout=None, server=None): ''' Use host to lookup addresses :param name: Name of record to search :param server: Server to query :param rdtype: DNS record type :param timeout: server response wait :return: [] of records or False if error ''' cmd = 'hos...
Use dnspython to lookup addresses: param name: Name of record to search: param rdtype: DNS record type: param timeout: query timeout: param server: [] of server ( s ) to try in order: return: [] of records or False if error
def _lookup_dnspython(name, rdtype, timeout=None, servers=None, secure=None): ''' Use dnspython to lookup addresses :param name: Name of record to search :param rdtype: DNS record type :param timeout: query timeout :param server: [] of server(s) to try in order :return: [] of records or Fals...
Use nslookup to lookup addresses: param name: Name of record to search: param rdtype: DNS record type: param timeout: server response timeout: param server: server to query: return: [] of records or False if error
def _lookup_nslookup(name, rdtype, timeout=None, server=None): ''' Use nslookup to lookup addresses :param name: Name of record to search :param rdtype: DNS record type :param timeout: server response timeout :param server: server to query :return: [] of records or False if error ''' ...
Lookup DNS records and return their data
def lookup( name, rdtype, method=None, servers=None, timeout=None, walk=False, walk_tld=False, secure=None ): ''' Lookup DNS records and return their data :param name: name to lookup :param rdtype: DNS record type :param method: gai (getaddrinfo()), dnspython, dig, d...
Query DNS for information. Where lookup () returns record data query () tries to interpret the data and return it s results
def query( name, rdtype, method=None, servers=None, timeout=None, walk=False, walk_tld=False, secure=None ): ''' Query DNS for information. Where `lookup()` returns record data, `query()` tries to interpret the data and return it's results :param name: name to lookup ...
Return a list of addresses for name
def host(name, ip4=True, ip6=True, **kwargs): ''' Return a list of addresses for name ip6: Return IPv6 addresses ip4: Return IPv4 addresses the rest is passed on to lookup() ''' res = {} if ip6: ip6 = lookup(name, 'AAAA', **kwargs) if ip6: re...
Validate and parse DNS record data for a CAA record: param rdata: DNS record data: return: dict w/ fields
def caa_rec(rdatas): ''' Validate and parse DNS record data for a CAA record :param rdata: DNS record data :return: dict w/fields ''' rschema = OrderedDict(( ('flags', lambda flag: ['critical'] if int(flag) > 0 else []), ('tag', RFC.CAA_TAGS), ('value', lambda val: val.st...
Return PTR name of given IP: param rdata: IP address: return: PTR record name
def ptr_name(rdata): ''' Return PTR name of given IP :param rdata: IP address :return: PTR record name ''' try: return ipaddress.ip_address(rdata).reverse_pointer except ValueError: log.error( 'Unable to generate PTR record; %s is not a valid IP address', ...
Validate and parse DNS record data for SOA record ( s ): param rdata: DNS record data: return: dict w/ fields
def soa_rec(rdata): ''' Validate and parse DNS record data for SOA record(s) :param rdata: DNS record data :return: dict w/fields ''' rschema = OrderedDict(( ('mname', str), ('rname', str), ('serial', int), ('refresh', int), ('retry', int), ('expir...
Validate and parse DNS record data for SPF record ( s ): param rdata: DNS record data: return: dict w/ fields
def spf_rec(rdata): ''' Validate and parse DNS record data for SPF record(s) :param rdata: DNS record data :return: dict w/fields ''' spf_fields = rdata.split(' ') if not spf_fields.pop(0).startswith('v=spf'): raise ValueError('Not an SPF record') res = OrderedDict() mods = ...
Generate SRV record data: param target:: param port:: param prio:: param weight:: return:
def srv_data(target, port, prio=10, weight=10): ''' Generate SRV record data :param target: :param port: :param prio: :param weight: :return: ''' return _rec2data(prio, weight, port, target)
Generate SRV record name: param svc: ldap 389 etc: param proto: tcp udp sctp etc.: param domain: name to append: return:
def srv_name(svc, proto='tcp', domain=None): ''' Generate SRV record name :param svc: ldap, 389 etc :param proto: tcp, udp, sctp etc. :param domain: name to append :return: ''' proto = RFC.validate(proto, RFC.SRV_PROTO) if isinstance(svc, int) or svc.isdigit(): svc = _to_port...
Validate and parse DNS record data for SRV record ( s ): param rdata: DNS record data: return: dict w/ fields
def srv_rec(rdatas): ''' Validate and parse DNS record data for SRV record(s) :param rdata: DNS record data :return: dict w/fields ''' rschema = OrderedDict(( ('prio', int), ('weight', int), ('port', _to_port), ('name', str), )) return _data2rec_group(rsch...
Generate an SSHFP record: param key_t: rsa/ dsa/ ecdsa/ ed25519: param hash_t: sha1/ sha256: param pub: the SSH public key
def sshfp_data(key_t, hash_t, pub): ''' Generate an SSHFP record :param key_t: rsa/dsa/ecdsa/ed25519 :param hash_t: sha1/sha256 :param pub: the SSH public key ''' key_t = RFC.validate(key_t, RFC.SSHFP_ALGO, 'in') hash_t = RFC.validate(hash_t, RFC.SSHFP_HASH) hasher = hashlib.new(has...
Validate and parse DNS record data for TLSA record ( s ): param rdata: DNS record data: return: dict w/ fields
def sshfp_rec(rdata): ''' Validate and parse DNS record data for TLSA record(s) :param rdata: DNS record data :return: dict w/fields ''' rschema = OrderedDict(( ('algorithm', RFC.SSHFP_ALGO), ('fp_hash', RFC.SSHFP_HASH), ('fingerprint', lambda val: val.lower()) # resolve...
Generate a TLSA rec: param pub: Pub key in PEM format: param usage:: param selector:: param matching:: return: TLSA data portion
def tlsa_data(pub, usage, selector, matching): ''' Generate a TLSA rec :param pub: Pub key in PEM format :param usage: :param selector: :param matching: :return: TLSA data portion ''' usage = RFC.validate(usage, RFC.TLSA_USAGE) selector = RFC.validate(selector, RFC.TLSA_SELECT) ...
Validate and parse DNS record data for TLSA record ( s ): param rdata: DNS record data: return: dict w/ fields
def tlsa_rec(rdata): ''' Validate and parse DNS record data for TLSA record(s) :param rdata: DNS record data :return: dict w/fields ''' rschema = OrderedDict(( ('usage', RFC.TLSA_USAGE), ('selector', RFC.TLSA_SELECT), ('matching', RFC.TLSA_MATCHING), ('pub', str) ...
Find an SRV service in a domain or it s parents: param svc: service to find ( ldap 389 etc ): param proto: protocol the service talks ( tcp udp etc ): param domain: domain to start search in: param walk: walk the parents if domain doesn t provide the service: param secure: only return DNSSEC - validated results: return...
def service( svc, proto='tcp', domain=None, walk=False, secure=None ): ''' Find an SRV service in a domain or it's parents :param svc: service to find (ldap, 389, etc) :param proto: protocol the service talks (tcp, udp, etc) :param domain: domain to start search in :param wal...
Parse through system - known services: return: { svc: [ { port: port proto: proto desc: comment } ] }
def services(services_file='/etc/services'): ''' Parse through system-known services :return: { 'svc': [ { 'port': port 'proto': proto, 'desc': comment }, ], } ''' res = {} with salt.utils.files.fopen(services_file, 'r') as svc_d...
Parse a resolver configuration file ( traditionally/ etc/ resolv. conf )
def parse_resolv(src='/etc/resolv.conf'): ''' Parse a resolver configuration file (traditionally /etc/resolv.conf) ''' nameservers = [] ip4_nameservers = [] ip6_nameservers = [] search = [] sortlist = [] domain = '' options = [] try: with salt.utils.files.fopen(src)...
Get the returner options from salt.
def get_returner_options(virtualname=None, ret=None, attrs=None, **kwargs): ''' Get the returner options from salt. :param str virtualname: The returner virtualname (as returned by __virtual__() :param ret: result of the...
Fetch a given option value from the config.
def _fetch_option(cfg, ret_config, virtualname, attr_name): """ Fetch a given option value from the config. @see :func:`get_returner_options` """ # c_cfg is a dictionary returned from config.option for # any options configured for this returner. if isinstance(cfg, dict): c_cfg = cfg...
Iterator generating all duples option name - > value
def _options_browser(cfg, ret_config, defaults, virtualname, options): """ Iterator generating all duples ```option name -> value``` @see :func:`get_returner_options` """ for option in options: # default place for the option in the config value = _fetch_option(cfg, ret_config, vir...
Fetches profile specific options if applicable
def _fetch_profile_opts( cfg, virtualname, __salt__, _options, profile_attr, profile_attrs ): """ Fetches profile specific options if applicable @see :func:`get_returner_options` :return: a options dict """ if (not profile_attr) or (profile_attr not...
Ensure the RabbitMQ plugin is enabled.
def enabled(name, runas=None): ''' Ensure the RabbitMQ plugin is enabled. name The name of the plugin runas The user to run the rabbitmq-plugin command as ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} try: plugin_enabled = __salt__['rabbitm...
Shorthand helper function for comparing SHA1s. If rev_type == sha1 then the comparison will be done using str. startwith () to allow short SHA1s to compare successfully.
def _revs_equal(rev1, rev2, rev_type): ''' Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev. ''' if (rev1 is None and rev...
DRY helper to build list of opts for git. branch for the purposes of setting upstream tracking branch
def _get_branch_opts(branch, local_branch, all_local_branches, desired_upstream, git_ver=None): ''' DRY helper to build list of opts for git.branch, for the purposes of setting upstream tracking branch ''' if branch is not None and branch not in all_local_branches: # We ...
Return the local revision for before/ after comparisons
def _get_local_rev_and_branch(target, user, password, output_encoding=None): ''' Return the local revision for before/after comparisons ''' log.info('Checking local revision for %s', target) try: local_rev = __salt__['git.revision']( target, user=user, pas...
Ensure that a repository exists in the given directory
def present(name, force=False, bare=True, template=None, separate_git_dir=None, shared=None, user=None, password=None, output_encoding=None): ''' Ensure that a repository exists in the given directory .. warning...
.. versionadded:: 2016. 3. 0
def detached(name, rev, target=None, remote='origin', user=None, password=None, force_clone=False, force_checkout=False, fetch_remote=True, hard_reset=False, submodules=False, identity=None, ...
.. versionadded:: 2018. 3. 3 2019. 2. 0
def cloned(name, target=None, branch=None, user=None, password=None, identity=None, https_user=None, https_pass=None, output_encoding=None): ''' .. versionadded:: 2018.3.3,2019.2.0 Ensure that a repository has been clon...
r.. versionadded:: 2015. 8. 0
def config_unset(name, value_regex=None, repo=None, user=None, password=None, output_encoding=None, **kwargs): r''' .. versionadded:: 2015.8.0 Ensure that the named config key is not present name ...
.. versionadded:: 2014. 7. 0.. versionchanged:: 2015. 8. 0 Renamed from git. config to git. config_set. For earlier versions use git. config.
def config_set(name, value=None, multivar=None, repo=None, user=None, password=None, output_encoding=None, **kwargs): ''' .. versionadded:: 2014.7.0 .. versionchanged:: 2015.8.0 Renamed from ``gi...
Execute the onlyif and unless logic. Return a result dict if:
def mod_run_check(cmd_kwargs, onlyif, unless): ''' Execute the onlyif and unless logic. Return a result dict if: * onlyif failed (onlyif != 0) * unless succeeded (unless == 0) Otherwise, returns ``True`` ''' cmd_kwargs = copy.deepcopy(cmd_kwargs) cmd_kwargs.update({ 'use_vt': F...
Pushing a text note.
def push_note(device=None, title=None, body=None): ''' Pushing a text note. :param device: Pushbullet target device :param title: Note title :param body: Note body :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt "...
Verify the webhook signature from travisci
def verify_webhook(signature, body): ''' Verify the webhook signature from travisci signature The signature header from the webhook header body The full payload body from the webhook post .. note:: The body needs to be the urlencoded version of the body. CLI Example: .. ...
Ensure that the named interface is configured properly.
def managed(name, type, enabled=True, **kwargs): ''' Ensure that the named interface is configured properly. name The name of the interface to manage type Type of interface and configuration. enabled Designates the state of this interface. kwargs The IP parame...
Manage network interface static routes.
def routes(name, **kwargs): ''' Manage network interface static routes. name Interface name to apply the route to. kwargs Named routes ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': 'Interface {0} routes are up to date.'.form...
Ensure that global network settings are configured properly.
def system(name, **kwargs): ''' Ensure that global network settings are configured properly. name Custom name to represent this configuration change. kwargs The global parameters for the system. ''' ret = { 'name': name, 'changes': {}, 'result': True, ...
Creates new mediatype. NOTE: This function accepts all standard mediatype properties: keyword argument names differ depending on your zabbix version see: https:// www. zabbix. com/ documentation/ 3. 0/ manual/ api/ reference/ host/ object#host_inventory
def present(name, mediatype, **kwargs): ''' Creates new mediatype. NOTE: This function accepts all standard mediatype properties: keyword argument names differ depending on your zabbix version, see: https://www.zabbix.com/documentation/3.0/manual/api/reference/host/object#host_inventory :param ...
Ensures that the mediatype does not exist eventually deletes the mediatype.
def absent(name, **kwargs): ''' Ensures that the mediatype does not exist, eventually deletes the mediatype. :param name: name of the mediatype :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix ...
Sanitize host string. https:// tools. ietf. org/ html/ rfc1123#section - 2. 1
def sanitize_host(host): ''' Sanitize host string. https://tools.ietf.org/html/rfc1123#section-2.1 ''' RFC952_characters = ascii_letters + digits + ".-" return "".join([c for c in host[0:255] if c in RFC952_characters])
Return status of a port
def isportopen(host, port): ''' Return status of a port ''' if not 1 <= int(port) <= 65535: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) out = sock.connect_ex((sanitize_host(host), int(port))) return out
Returns a list of IP addresses of a given hostname or None if not found.
def host_to_ips(host): ''' Returns a list of IP addresses of a given hostname or None if not found. ''' ips = [] try: for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM): if family == socket.AF_INE...
Get list of possible host names and convention names.
def _generate_minion_id(): ''' Get list of possible host names and convention names. :return: ''' # There are three types of hostnames: # 1. Network names. How host is accessed from the network. # 2. Host aliases. They might be not available in all the network or only locally (/etc/hosts) ...
Return only first element of the hostname from all possible list.
def generate_minion_id(): ''' Return only first element of the hostname from all possible list. :return: ''' try: ret = salt.utils.stringutils.to_unicode(_generate_minion_id().first()) except TypeError: ret = None return ret or 'localhost'
Return a socket object for the addr IP - version agnostic
def get_socket(addr, type=socket.SOCK_STREAM, proto=0): ''' Return a socket object for the addr IP-version agnostic ''' version = ipaddress.ip_address(addr).version if version == 4: family = socket.AF_INET elif version == 6: family = socket.AF_INET6 return socket.socket(...
Returns the fully qualified hostname
def get_fqhostname(): ''' Returns the fully qualified hostname ''' # try getaddrinfo() fqdn = None try: addrinfo = socket.getaddrinfo( socket.gethostname(), 0, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME ) for info in ...
Returns the hostname of a given IP
def ip_to_host(ip): ''' Returns the hostname of a given IP ''' try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except Exception as exc: log.debug('salt.utils.network.ip_to_host(%r) failed: %s', ip, exc) hostname = None return hostname
Returns a bool telling if the entity name is a reachable host ( IPv4/ IPv6/ FQDN/ etc ).: param hostname:: return:
def is_reachable_host(entity_name): ''' Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc). :param hostname: :return: ''' try: assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list ret = True except socket.gaierror: ret = Fal...
Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address.
def is_ip_filter(ip, options=None): ''' Returns a bool telling if the passed IP is a valid IPv4 or IPv6 address. ''' return is_ipv4_filter(ip, options=options) or is_ipv6_filter(ip, options=options)
Returns a bool telling if the value passed to it was a valid IPv4 address.
def is_ipv4_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv4 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, mult...
Returns a bool telling if the value passed to it was a valid IPv6 address.
def is_ipv6_filter(ip, options=None): ''' Returns a bool telling if the value passed to it was a valid IPv6 address. ip The IP address. net: False Consider IP addresses followed by netmask. options CSV of options regarding the nature of the IP address. E.g.: loopback, mult...
Filters and returns only valid IP objects.
def ipaddr(value, options=None): ''' Filters and returns only valid IP objects. ''' ipv4_obj = ipv4(value, options=options) ipv6_obj = ipv6(value, options=options) if ipv4_obj is None or ipv6_obj is None: # an IP address can be either IPv4 either IPv6 # therefofe if the value pas...
Returns the interfaces IP address e. g.: 192. 168. 0. 1/ 28.
def ip_host(value, options=None, version=None): ''' Returns the interfaces IP address, e.g.: 192.168.0.1/28. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): ...
Return the list of hosts within a network.
def network_hosts(value, options=None, version=None): ''' Return the list of hosts within a network. .. note:: When running this command with a large IPv6 network, the command will take a long time to gather all of the hosts. ''' ipaddr_filter_out = _filter_ipaddr(value, options=op...
Get the size of a network.
def network_size(value, options=None, version=None): ''' Get the size of a network. ''' ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version) if not ipaddr_filter_out: return if not isinstance(value, (list, tuple, types.GeneratorType)): return _network_size(...
Returns the natural mask of an IPv4 address
def natural_ipv4_netmask(ip, fmt='prefixlen'): ''' Returns the "natural" mask of an IPv4 address ''' bits = _ipv4_to_bits(ip) if bits.startswith('11'): mask = '24' elif bits.startswith('1'): mask = '16' else: mask = '8' if fmt == 'netmask': return cidr_t...
Returns an IPv4 netmask
def cidr_to_ipv4_netmask(cidr_bits): ''' Returns an IPv4 netmask ''' try: cidr_bits = int(cidr_bits) if not 1 <= cidr_bits <= 32: return '' except ValueError: return '' netmask = '' for idx in range(4): if idx: netmask += '.' i...
Returns the number of bits that are set in a 32bit int
def _number_of_set_bits(x): ''' Returns the number of bits that are set in a 32bit int ''' # Taken from http://stackoverflow.com/a/4912729. Many thanks! x -= (x >> 1) & 0x55555555 x = ((x >> 2) & 0x33333333) + (x & 0x33333333) x = ((x >> 4) + x) & 0x0f0f0f0f x += x >> 8 x += x >> 16 ...
Uses ifconfig to return a dictionary of interfaces with various information about each ( up/ down state ip address netmask and hwaddr )
def _interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]...
Obtain interface information for * NIX/ BSD variants
def linux_interfaces(): ''' Obtain interface information for *NIX/BSD variants ''' ifaces = dict() ip_path = salt.utils.path.which('ip') ifconfig_path = None if ip_path else salt.utils.path.which('ifconfig') if ip_path: cmd1 = subprocess.Popen( '{0} link show'.format(ip_p...
Uses ifconfig to return a dictionary of interfaces with various information about each ( up/ down state ip address netmask and hwaddr )
def _netbsd_interfaces_ifconfig(out): ''' Uses ifconfig to return a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) ''' ret = dict() piface = re.compile(r'^([^\s:]+)') pmac = re.compile('.*?address: ([0-9a-f:]+)') pip = re.c...
Obtain interface information for NetBSD > = 8 where the ifconfig output diverged from other BSD variants ( Netmask is now part of the address )
def netbsd_interfaces(): ''' Obtain interface information for NetBSD >= 8 where the ifconfig output diverged from other BSD variants (Netmask is now part of the address) ''' # NetBSD versions prior to 8.0 can still use linux_interfaces() if LooseVersion(os.uname()[2]) < LooseVersion('8.0'): ...
Returns a dictionary of interfaces with various information about each ( up/ down state ip address netmask and hwaddr )
def _interfaces_ipconfig(out): ''' Returns a dictionary of interfaces with various information about each (up/down state, ip address, netmask, and hwaddr) NOTE: This is not used by any function and may be able to be removed in the future. ''' ifaces = dict() iface = None adapter_ifa...
Obtain interface information for Windows systems
def win_interfaces(): ''' Obtain interface information for Windows systems ''' with salt.utils.winapi.Com(): c = wmi.WMI() ifaces = {} for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1): ifaces[iface.Description] = dict() if iface.MACAddress: ...
Return a dictionary of information about all the interfaces on the minion
def interfaces(): ''' Return a dictionary of information about all the interfaces on the minion ''' if salt.utils.platform.is_windows(): return win_interfaces() elif salt.utils.platform.is_netbsd(): return netbsd_interfaces() else: return linux_interfaces()
Return the address of the network
def get_net_start(ipaddr, netmask): ''' Return the address of the network ''' net = ipaddress.ip_network('{0}/{1}'.format(ipaddr, netmask), strict=False) return six.text_type(net.network_address)
Turns an IPv4 netmask into it s corresponding prefix length ( 255. 255. 255. 0 - > 24 as in 192. 168. 1. 10/ 24 ).
def get_net_size(mask): ''' Turns an IPv4 netmask into it's corresponding prefix length (255.255.255.0 -> 24 as in 192.168.1.10/24). ''' binary_str = '' for octet in mask.split('.'): binary_str += bin(int(octet))[2:].zfill(8) return len(binary_str.rstrip('0'))
Takes IP ( CIDR notation supported ) and optionally netmask and returns the network in CIDR - notation. ( The IP can be any IP inside the subnet )
def calc_net(ipaddr, netmask=None): ''' Takes IP (CIDR notation supported) and optionally netmask and returns the network in CIDR-notation. (The IP can be any IP inside the subnet) ''' if netmask is not None: ipaddr = '{0}/{1}'.format(ipaddr, netmask) return six.text_type(ipaddress....
Accepts an IPv4 dotted quad and returns a string representing its binary counterpart
def _ipv4_to_bits(ipaddr): ''' Accepts an IPv4 dotted quad and returns a string representing its binary counterpart ''' return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
If iface is available return interface info and no error otherwise return no info and log and return an error
def _get_iface_info(iface): ''' If `iface` is available, return interface info and no error, otherwise return no info and log and return an error ''' iface_info = interfaces() if iface in iface_info.keys(): return iface_info, False else: error_msg = ('Interface "{0}" not in ...
Return the hardware address ( a. k. a. MAC address ) for a given interface on AIX MAC address not available in through interfaces
def _hw_addr_aix(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface on AIX MAC address not available in through interfaces ''' cmd = subprocess.Popen( 'entstat -d {0} | grep \'Hardware Address\''.format(iface), shell=True, stdout=subprocess.PIP...
Return the hardware address ( a. k. a. MAC address ) for a given interface
def hw_addr(iface): ''' Return the hardware address (a.k.a. MAC address) for a given interface .. versionchanged:: 2016.11.4 Added support for AIX ''' if salt.utils.platform.is_aix(): return _hw_addr_aix iface_info, error = _get_iface_info(iface) if error is False: ...
Return the details of iface or an error if it does not exist
def interface(iface): ''' Return the details of `iface` or an error if it does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: return iface_info.get(iface, {}).get('inet', '') else: return error
Return iface IPv4 addr or an error if iface does not exist
def interface_ip(iface): ''' Return `iface` IPv4 addr or an error if `iface` does not exist ''' iface_info, error = _get_iface_info(iface) if error is False: inet = iface_info.get(iface, {}).get('inet', None) return inet[0].get('address', '') if inet else '' else: return...
Returns a list of subnets to which the host belongs
def _subnets(proto='inet', interfaces_=None): ''' Returns a list of subnets to which the host belongs ''' if interfaces_ is None: ifaces = interfaces() elif isinstance(interfaces_, list): ifaces = {} for key, value in six.iteritems(interfaces()): if key in interfa...
Returns True if host or ( any of ) addrs is within specified subnet otherwise False
def in_subnet(cidr, addr=None): ''' Returns True if host or (any of) addrs is within specified subnet, otherwise False ''' try: cidr = ipaddress.ip_network(cidr) except ValueError: log.error('Invalid CIDR \'%s\'', cidr) return False if addr is None: addr = ip_add...
Return the full list of IP adresses matching the criteria
def _ip_addrs(interface=None, include_loopback=False, interface_data=None, proto='inet'): ''' Return the full list of IP adresses matching the criteria proto = inet|inet6 ''' ret = set() ifaces = interface_data \ if isinstance(interface_data, dict) \ else interfaces() if in...
Convert a hex string to an ip if a failure occurs the original hex is returned. If invert = True assume that ip from/ proc/ net/ <proto >
def hex2ip(hex_ip, invert=False): ''' Convert a hex string to an ip, if a failure occurs the original hex is returned. If 'invert=True' assume that ip from /proc/net/<proto> ''' if len(hex_ip) == 32: # ipv6 ip = [] for i in range(0, 32, 8): ip_part = hex_ip[i:i + 8] ...
Convert a MAC address to a EUI64 identifier or with prefix provided a full IPv6 address
def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:...
Return a dict describing all active tcp connections as quickly as possible
def active_tcp(): ''' Return a dict describing all active tcp connections as quickly as possible ''' ret = {} for statf in ['/proc/net/tcp', '/proc/net/tcp6']: if os.path.isfile(statf): with salt.utils.files.fopen(statf, 'rb') as fp_: for line in fp_: ...
Return a set of ip addrs active tcp connections
def _remotes_on(port, which_end): ''' Return a set of ip addrs active tcp connections ''' port = int(port) ret = _netlink_tool_remote_on(port, which_end) if ret is not None: return ret ret = set() proc_available = False for statf in ['/proc/net/tcp', '/proc/net/tcp6']: ...
Parse a single line from the contents of/ proc/ net/ tcp or/ proc/ net/ tcp6
def _parse_tcp_line(line): ''' Parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 ''' ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} l_addr, l_port = comps[1].split(':') r_addr, r_port = comps[2].split(':') ret[sl]['local_addr']...
Returns set of ipv4 host addresses of remote established connections on local or remote tcp port.
def _netlink_tool_remote_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'ss' to get connections [root@salt-master ~]# ss -ant State Recv-Q Send-Q Local Address:Port ...
Returns set of ipv4 host addresses of remote established connections on local tcp port port.
def _netbsd_remotes_on(port, which_end): ''' Returns set of ipv4 host addresses of remote established connections on local tcp port port. Parses output of shell 'sockstat' (NetBSD) to get connections $ sudo sockstat -4 -n USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDR...
OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port.
def _openbsd_remotes_on(port, which_end): ''' OpenBSD specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections $ netstat -nf inet Active Internet connections Proto R...
r Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port.
def _windows_remotes_on(port, which_end): r''' Windows specific helper function. Returns set of ipv4 host addresses of remote established connections on local or remote tcp port. Parses output of shell 'netstat' to get connections C:\>netstat -n Active Connections Proto Local Add...
Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port.
def _linux_remotes_on(port, which_end): ''' Linux specific helper function. Returns set of ip host addresses of remote established connections on local tcp port port. Parses output of shell 'lsof' to get connections $ sudo lsof -iTCP:4505 -n COMMAND PID USER FD TYPE D...
Generates a MAC address with the defined OUI prefix.
def gen_mac(prefix='AC:DE:48'): ''' Generates a MAC address with the defined OUI prefix. Common prefixes: - ``00:16:3E`` -- Xen - ``00:18:51`` -- OpenVZ - ``00:50:56`` -- VMware (manually generated) - ``52:54:00`` -- QEMU/KVM - ``AC:DE:48`` -- PRIVATE References: - http...
Convert a MAC address string into bytes. Works with or without separators:
def mac_str_to_bytes(mac_str): ''' Convert a MAC address string into bytes. Works with or without separators: b1 = mac_str_to_bytes('08:00:27:13:69:77') b2 = mac_str_to_bytes('080027136977') assert b1 == b2 assert isinstance(b1, bytes) ''' if len(mac_str) == 12: pass elif le...
Provides a convenient alias for the dns_check filter.
def connection_check(addr, port=80, safe=False, ipv6=None): ''' Provides a convenient alias for the dns_check filter. ''' return dns_check(addr, port, safe, ipv6)