Python ipaddress.summarize_address_range() Examples

The following are 10 code examples of ipaddress.summarize_address_range(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipaddress , or try the search function .
Example #1
Source File: ip.py    From CrackMapExec with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def parse_targets(target):
    try:
        if '-' in target:
            start_ip, end_ip = target.split('-')
            try:
                end_ip = ip_address(end_ip)
            except ValueError:
                first_three_octets = start_ip.split(".")[:-1]
                first_three_octets.append(end_ip)
                end_ip = ip_address(
                            ".".join(first_three_octets)
                        )

            for ip_range in summarize_address_range(ip_address(start_ip), end_ip):
                for ip in ip_range:
                    yield str(ip)
        else:
            for ip in ip_network(target, strict=False):
                yield str(ip)
    except ValueError:
        yield str(target) 
Example #2
Source File: parsers.py    From WitnessMe with GNU General Public License v3.0 6 votes vote down vote up
def expand_ip_cidr_or_range(self, target):
        try:
            if '-' in target:
                start_ip, end_ip = target.split('-')
                try:
                    end_ip = ip_address(end_ip)
                except ValueError:
                    first_three_octets = start_ip.split(".")[:-1]
                    first_three_octets.append(end_ip)
                    end_ip = ip_address(
                                ".".join(first_three_octets)
                            )

                for ip_range in summarize_address_range(ip_address(start_ip), end_ip):
                    for ip in ip_range:
                        yield str(ip)
            else:
                for ip in ip_network(target, strict=False):
                    yield str(ip)
        except ValueError:
            yield str(target) 
Example #3
Source File: ipwhois.py    From machinae with MIT License 5 votes vote down vote up
def get_cidr(network):
        networks = [str(net) for net in summarize_address_range(
            ip_address(network["start_address"]),
            ip_address(network["end_address"])
        )]
        if len(networks) == 1:
            networks = networks[0]
        return networks 
Example #4
Source File: whois_miner.py    From recon-ng-marketplace with GNU General Public License v3.0 5 votes vote down vote up
def module_run(self, searches):
        headers = {'Accept': 'application/json'}
        for search in searches:
            for rtype in ('org', 'customer'):
                url = f"http://whois.arin.net/rest/{rtype}s;name={quote(search)}"
                entities = self._request(url, headers, rtype+'s', rtype+'Ref')
                for entity in entities:
                    self.heading(entity['@name'], level=0)
                    url = entity['$']
                    resp = self.request('GET', url, headers=headers)
                    # add company
                    self.insert_companies(company=entity['@name'], description=rtype)
                    # add location
                    location = WhoisLocation(resp.json()[rtype])
                    self.insert_locations(street_address=location.address)
                    # add netblocks
                    url = f"http://whois.arin.net/rest/{rtype}/{entity['@handle']}/nets"
                    nets = self._request(url, headers, 'nets', 'netRef')
                    for net in nets:
                        start = ipaddress.ip_address(net['@startAddress'])
                        end = ipaddress.ip_address(net['@endAddress'])
                        blocks = ipaddress.summarize_address_range(start, end)
                        for block in blocks:
                            self.insert_netblocks(netblock=str(block))
                    # add contacts
                    url = f"http://whois.arin.net/rest/{rtype}/{entity['@handle']}/pocs"
                    pocLinks = self._request(url, headers, 'pocs', 'pocLinkRef')
                    for pocLink in pocLinks:
                        url = pocLink['$']
                        resp = self.request('GET', url, headers=headers)
                        poc = resp.json()['poc']
                        emails = _enum_ref(poc['emails']['email'])
                        for email in emails:
                            fname = poc['firstName']['$'] if 'firstName' in poc else None
                            lname = poc['lastName']['$']
                            name = ' '.join([x for x in [fname, lname] if x])
                            email = email['$']
                            title = f"Whois contact ({pocLink['@description']})"
                            location = WhoisLocation(poc)
                            self.insert_contacts(first_name=fname, last_name=lname, email=email, title=title, region=location.region, country=location.country) 
Example #5
Source File: registry.py    From console with MIT License 5 votes vote down vote up
def ip_in_whitelist(ip):
    try:
        logger.debug("client ip request for registry auth is %s" % ip)
        white_ips = [x.strip() for x in REGISTRY_IP_WHITELIST.split(',')]
        networks, ranges, ips = [], [], []
        for ip_str in white_ips:
            if ip_str.find('/') >= 0:
                try:
                    networks.append(ipaddress.ip_network(unicode(ip_str)))
                except Exception as e:
                    logger.warning("format of ip net %s is invalid" % ip_str)
            elif ip_str.find('-') >= 0:
                try:
                    first, last = ip_str.split('-')
                    ranges.append(ipaddress.summarize_address_range(
                        IPv4Address(unicode(first)), IPv4Address(unicode(last))))
                except Exception as e:
                    logger.warning("format of ip range %s is invalid" % ip_str)
            else:
                ips.append(ip_str)
        if ip in ips:
            return True
        for ip_range in ranges:
            if IPv4Address(ip) in ip_range:
                return True
        for network in networks:
            if IPv4Address(ip) in network:
                return True
        return IPAddress(ip) in IPNetwork(NODE_NETWORK)
    except Exception, e:
        logger.error(
            "Exception parse registry whitelist for ip %s : %s" % (ip, str(e)))
        return False 
Example #6
Source File: test_ipaddress.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def testSummarizing(self):
        #ip = ipaddress.ip_address
        #ipnet = ipaddress.ip_network
        summarize = ipaddress.summarize_address_range
        ip1 = ipaddress.ip_address('1.1.1.0')
        ip2 = ipaddress.ip_address('1.1.1.255')

        # summarize works only for IPv4 & IPv6
        class IPv7Address(ipaddress.IPv6Address):
            @property
            def version(self):
                return 7
        ip_invalid1 = IPv7Address('::1')
        ip_invalid2 = IPv7Address('::1')
        self.assertRaises(ValueError, list,
                          summarize(ip_invalid1, ip_invalid2))
        # test that a summary over ip4 & ip6 fails
        self.assertRaises(TypeError, list,
                          summarize(ip1, ipaddress.IPv6Address('::1')))
        # test a /24 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1.1.1.0/24'))
        # test an IPv4 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('1.1.1.8')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1.1.1.0/29'),
                          ipaddress.ip_network('1.1.1.8')])
        # all!
        ip1 = ipaddress.IPv4Address(0)
        ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
        self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
                         list(summarize(ip1, ip2)))

        ip1 = ipaddress.ip_address('1::')
        ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
        # test an IPv6 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1::/16'))
        # test an IPv6 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('2::')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1::/16'),
                          ipaddress.ip_network('2::/128')])

        # test exception raised when first is greater than last
        self.assertRaises(ValueError, list,
                          summarize(ipaddress.ip_address('1.1.1.0'),
                                    ipaddress.ip_address('1.1.0.0')))
        # test exception raised when first and last aren't IP addresses
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        # test exception raised when first and last are not same version
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_address('::'),
                                    ipaddress.ip_network('1.1.0.0'))) 
Example #7
Source File: test_ipaddress.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def testSummarizing(self):
        #ip = ipaddress.ip_address
        #ipnet = ipaddress.ip_network
        summarize = ipaddress.summarize_address_range
        ip1 = ipaddress.ip_address('1.1.1.0')
        ip2 = ipaddress.ip_address('1.1.1.255')

        # summarize works only for IPv4 & IPv6
        class IPv7Address(ipaddress.IPv6Address):
            @property
            def version(self):
                return 7
        ip_invalid1 = IPv7Address('::1')
        ip_invalid2 = IPv7Address('::1')
        self.assertRaises(ValueError, list,
                          summarize(ip_invalid1, ip_invalid2))
        # test that a summary over ip4 & ip6 fails
        self.assertRaises(TypeError, list,
                          summarize(ip1, ipaddress.IPv6Address('::1')))
        # test a /24 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1.1.1.0/24'))
        # test an IPv4 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('1.1.1.8')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1.1.1.0/29'),
                          ipaddress.ip_network('1.1.1.8')])
        # all!
        ip1 = ipaddress.IPv4Address(0)
        ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
        self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
                         list(summarize(ip1, ip2)))

        ip1 = ipaddress.ip_address('1::')
        ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
        # test an IPv6 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1::/16'))
        # test an IPv6 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('2::')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1::/16'),
                          ipaddress.ip_network('2::/128')])

        # test exception raised when first is greater than last
        self.assertRaises(ValueError, list,
                          summarize(ipaddress.ip_address('1.1.1.0'),
                                    ipaddress.ip_address('1.1.0.0')))
        # test exception raised when first and last aren't IP addresses
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        # test exception raised when first and last are not same version
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_address('::'),
                                    ipaddress.ip_network('1.1.0.0'))) 
Example #8
Source File: overcloud_netenv_validate.py    From python-tripleoclient with Apache License 2.0 4 votes vote down vote up
def check_allocation_pools_pairing(self, filedata, pools):
        for poolitem in pools:
            pooldata = filedata[poolitem]

            self.log.info('Checking allocation pool {}'.format(poolitem))

            pool_objs = []
            for pool in pooldata:
                try:
                    ip_start = ipaddress.ip_address(
                        six.u(pool['start']))
                except ValueError:
                    self.log.error('Invalid address: %s' % ip_start)
                    self.error_count += 1
                    ip_start = None
                try:
                    ip_end = ipaddress.ip_address(six.u(pool['end']))
                except ValueError:
                    self.log.error('Invalid address: %s' % ip_start)
                    self.error_count += 1
                    ip_end = None
                if (ip_start is None) or (ip_end is None):
                    continue
                try:
                    pool_objs.append(list(
                        ipaddress.summarize_address_range(ip_start, ip_end)))
                except Exception:
                    self.log.error('Invalid address pool: %s, %s' %
                                   (ip_start, ip_end))
                    self.error_count += 1

            subnet_item = poolitem.split('AllocationPools')[0] + 'NetCidr'
            try:
                subnet_obj = ipaddress.ip_network(
                    six.u(filedata[subnet_item]))
            except ValueError:
                self.log.error('Invalid address: %s', subnet_item)
                self.error_count += 1
                continue

            for ranges in pool_objs:
                for range in ranges:
                    if not subnet_obj.overlaps(range):
                        self.log.error(
                            'Allocation pool {} {} outside of subnet {}: {}'
                            .format(poolitem, pooldata, subnet_item,
                                    subnet_obj))
                        self.error_count += 1
                        break 
Example #9
Source File: test_ipaddress.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 4 votes vote down vote up
def testSummarizing(self):
        #ip = ipaddress.ip_address
        #ipnet = ipaddress.ip_network
        summarize = ipaddress.summarize_address_range
        ip1 = ipaddress.ip_address('1.1.1.0')
        ip2 = ipaddress.ip_address('1.1.1.255')

        # summarize works only for IPv4 & IPv6
        class IPv7Address(ipaddress.IPv6Address):
            @property
            def version(self):
                return 7
        ip_invalid1 = IPv7Address('::1')
        ip_invalid2 = IPv7Address('::1')
        self.assertRaises(ValueError, list,
                          summarize(ip_invalid1, ip_invalid2))
        # test that a summary over ip4 & ip6 fails
        self.assertRaises(TypeError, list,
                          summarize(ip1, ipaddress.IPv6Address('::1')))
        # test a /24 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1.1.1.0/24'))
        # test an IPv4 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('1.1.1.8')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1.1.1.0/29'),
                          ipaddress.ip_network('1.1.1.8')])
        # all!
        ip1 = ipaddress.IPv4Address(0)
        ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
        self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
                         list(summarize(ip1, ip2)))

        ip1 = ipaddress.ip_address('1::')
        ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
        # test an IPv6 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1::/16'))
        # test an IPv6 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('2::')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1::/16'),
                          ipaddress.ip_network('2::/128')])

        # test exception raised when first is greater than last
        self.assertRaises(ValueError, list,
                          summarize(ipaddress.ip_address('1.1.1.0'),
                                    ipaddress.ip_address('1.1.0.0')))
        # test exception raised when first and last aren't IP addresses
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        # test exception raised when first and last are not same version
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_address('::'),
                                    ipaddress.ip_network('1.1.0.0'))) 
Example #10
Source File: test_ipaddress.py    From android_universal with MIT License 4 votes vote down vote up
def testSummarizing(self):
        #ip = ipaddress.ip_address
        #ipnet = ipaddress.ip_network
        summarize = ipaddress.summarize_address_range
        ip1 = ipaddress.ip_address('1.1.1.0')
        ip2 = ipaddress.ip_address('1.1.1.255')

        # summarize works only for IPv4 & IPv6
        class IPv7Address(ipaddress.IPv6Address):
            @property
            def version(self):
                return 7
        ip_invalid1 = IPv7Address('::1')
        ip_invalid2 = IPv7Address('::1')
        self.assertRaises(ValueError, list,
                          summarize(ip_invalid1, ip_invalid2))
        # test that a summary over ip4 & ip6 fails
        self.assertRaises(TypeError, list,
                          summarize(ip1, ipaddress.IPv6Address('::1')))
        # test a /24 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1.1.1.0/24'))
        # test an IPv4 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('1.1.1.8')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1.1.1.0/29'),
                          ipaddress.ip_network('1.1.1.8')])
        # all!
        ip1 = ipaddress.IPv4Address(0)
        ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
        self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
                         list(summarize(ip1, ip2)))

        ip1 = ipaddress.ip_address('1::')
        ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
        # test an IPv6 is summarized properly
        self.assertEqual(list(summarize(ip1, ip2))[0],
                         ipaddress.ip_network('1::/16'))
        # test an IPv6 range that isn't on a network byte boundary
        ip2 = ipaddress.ip_address('2::')
        self.assertEqual(list(summarize(ip1, ip2)),
                         [ipaddress.ip_network('1::/16'),
                          ipaddress.ip_network('2::/128')])

        # test exception raised when first is greater than last
        self.assertRaises(ValueError, list,
                          summarize(ipaddress.ip_address('1.1.1.0'),
                                    ipaddress.ip_address('1.1.0.0')))
        # test exception raised when first and last aren't IP addresses
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_network('1.1.1.0'),
                                    ipaddress.ip_network('1.1.0.0')))
        # test exception raised when first and last are not same version
        self.assertRaises(TypeError, list,
                          summarize(ipaddress.ip_address('::'),
                                    ipaddress.ip_network('1.1.0.0')))