Пример #1
0
    def GenerateDefinition(self, config, unused_global_config):
        """Generates a list of all nodes in a network definition.

    This method basically processes all the configuration which is
    hierarchically below "networks" in the "definitions" section in the
    configuration file to generate a list of all nodes in that definition.

    Args:
      config: YAML configuration structure (dictionaries, lists and strings)
        representing the "networks" section in "definitions" of the
        configuration file.
      unused_global_config: YAML configuration structure (dictionaries, lists
        and strings) representing the "global" section of the configuration
        file.

    Returns:
      Tuples of IPNetwork objects and string comments representing all the nodes
      in one definition.

    Raises:
      DefinateConfigError: The configuration is not well formed.
      DnsGeneratorError: There is a problem generating the output.
    """
        nodes = []
        yaml_structure = {
            'names': ['str'],
            'types': ['str'],
        }
        for network in config:
            self._yaml_validator.CheckConfiguration(network, yaml_structure)
            for typ in network['types']:
                if typ not in self.SUPPORTED_TYPES:
                    raise DnsGeneratorError('Unsupported DNS type found: %s' %
                                            typ)
            for name in network['names']:
                try:
                    addr_list = socket.getaddrinfo(name, None)
                except socket.gaierror:
                    raise DnsGeneratorError('Hostname not found: %s' % name)
                for family, _, _, _, sockaddr in addr_list:
                    ip_addr = None
                    if family == socket.AF_INET and 'A' in network['types']:
                        # sockaddr = (address, port)
                        ip_addr = ipaddr.IPv4Network(sockaddr[0])
                    elif family == socket.AF_INET6 and 'AAAA' in network[
                            'types']:
                        # sockaddr = (address, port, flow info, scope id)
                        ip_addr = ipaddr.IPv6Network(sockaddr[0])
                    else:
                        logging.debug('Skipping unknown AF \'%d\' for: %s',
                                      family, name)
                    if ip_addr:
                        nodes.append((ip_addr, name))
        return nodes
Пример #2
0
def IPv4Descriptor(desc):
    """Take an IP or Network or Range and returns appropriate lists.

    Args:
        desc: A String, that describes one or more IPv4 ranges,
            addresses or networks

    Returns:
        A list of IPv4Network objects.

    Raises:
        ValueError: if the string could not be parsed

    """
    iplist = []

    for addrblock in desc.split(';'):
        # Try to use ipaddr to parse standard conform notations:
        try:
            iplist.append(ipaddr.IPv4Address(addrblock))
            continue
        except (AddressValueError, NetmaskValueError):
            pass

        try:
            iplist.append(ipaddr.IPv4Network(addrblock))
            continue
        except (AddressValueError, NetmaskValueError):
            pass

        # Parsing non-standard notations:
        octets = addrblock.split('.')
        lastoct = octets[-1]

        for block in lastoct.split(','):
            if '-' in block:
                start, end = block.split('-')
                startaddr = ipaddr.IPv4Address('.'.join(octets[:-1]) + '.' +
                                               start)
                endaddr = ipaddr.IPv4Address('.'.join(octets[:-1]) + '.' + end)

                iplist += map(ipaddr.IPv4Address,
                              range(int(startaddr), int(endaddr + 1)))
            else:
                iplist.append(
                    ipaddr.IPv4Address('.'.join(octets[:-1]) + '.' + block))

    return ipaddr.collapse_address_list(iplist)
Пример #3
0
#!/usr/bin/python
'''An extension to ipaddr.py by Google Inc. to support non-standard, but
intuitive ip notations

This library extension aims to support the following ip notations:
IPv4:
 * , Notation (127.0.0.1,6 -> includes 127.0.0.1 and 127.0.0.6)
 * - Notation (172.0.0.1-3 -> includes 172.0.0.1, 172.0.0.2 and 172.0.0.3)
'''

from third_party import ipaddr
from third_party.ipaddr import AddressValueError as AddressValueError
from third_party.ipaddr import NetmaskValueError as NetmaskValueError

any_ = [ipaddr.IPv4Network('0.0.0.0/0'), ipaddr.IPv6Network('::1/0')]


def IPv4Descriptor(desc):
    """Take an IP or Network or Range and returns appropriate lists.

    Args:
        desc: A String, that describes one or more IPv4 ranges,
            addresses or networks

    Returns:
        A list of IPv4Network objects.

    Raises:
        ValueError: if the string could not be parsed

    """
Пример #4
0
parser.add_argument('--host',
                    help='Display the split as HOST (/32)',
                    action='store_true')
args = parser.parse_args()

dsmo_net = args.network

if len(dsmo_net.split('/')) != 2 or len(dsmo_net.split('.')) != 7:
    print 'ERROR: Format of network not valid. It should be in the format X.X.X.X/Y.Y.Y.Y'
    quit()

only_host = args.host

net_split = tools.split_non_contiguous(
    dsmo_net.split('/')[0],
    dsmo_net.split('/')[1])

for net in net_split:
    ip = net.split('/')[0]
    netmask = tools.mask_to_wild(net.split('/')[1])
    if only_host:
        if '/0.0.0.0' in net:
            # 0.0.0.0 in wildcard is host but in also means ANY is 'standard' way
            net = net.split('/')[0] + '/255.255.255.255'
        ip = ipaddr.IPv4Network(net)
        for host in list(ip):
            ip_host = str(host)
            print ip_host
    else:
        print ip + '/' + netmask