Python netaddr.IPRange() Examples

The following are 30 code examples of netaddr.IPRange(). 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 netaddr , or try the search function .
Example #1
Source File: prometheus_openstack_exporter.py    From prometheus-openstack-exporter with GNU General Public License v3.0 6 votes vote down vote up
def gen_subnet_size(self):
        labels = ['cloud', 'network_name']
        net_size = Gauge('neutron_net_size',
                         'Neutron networks size',
                         labels, registry=self.registry)
        for n in self.prodstack['networks']:
            size = 0
            for subnet in n['subnets']:
                for pool in self.subnet_map[subnet]['pool']:
                    if ':' in pool['start']:
                        # Skip IPv6 address pools; they are big enough to
                        # drown the IPv4 numbers we might care about.
                        continue
                    size += IPRange(pool['start'], pool['end']).size
            label_values = [config['cloud'], self.network_map[n['id']]]
            net_size.labels(*label_values).set(size) 
Example #2
Source File: ip_range.py    From clapper with Apache License 2.0 6 votes vote down vote up
def main():
    module = AnsibleModule(argument_spec=dict(
        start=dict(required=True, type='str'),
        end=dict(required=True, type='str'),
        min_size=dict(required=True, type='int'),
    ))

    start = module.params.get('start')
    end = module.params.get('end')

    iprange = netaddr.IPRange(start, end)

    if len(iprange) < module.params.get('min_size'):
        module.exit_json(
            changed=True,
            warnings=[
                'The IP range {} - {} contains {} addresses.'.format(
                    start, end, len(iprange)),
                'This might not be enough for the deployment or later scaling.'
            ])
    else:
        module.exit_json(msg='success') 
Example #3
Source File: ip_range.py    From clapper with Apache License 2.0 6 votes vote down vote up
def main():
    module = AnsibleModule(argument_spec=dict(
        start=dict(required=True, type='str'),
        end=dict(required=True, type='str'),
        min_size=dict(required=True, type='int'),
    ))

    start = module.params.get('start')
    end = module.params.get('end')

    iprange = netaddr.IPRange(start, end)

    if len(iprange) < module.params.get('min_size'):
        module.exit_json(
            changed=True,
            warnings=[
                'The IP range {} - {} contains {} addresses.'.format(
                    start, end, len(iprange)),
                'This might not be enough for the deployment or later scaling.'
            ])
    else:
        module.exit_json(msg='success') 
Example #4
Source File: network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def make_iprange(first, second=None, purpose="unknown") -> MAASIPRange:
    """Returns a MAASIPRange (which is compatible with IPRange) for the
    specified range of addresses.

    :param second: the (inclusive) upper bound of the range. If not supplied,
        uses the lower bound (creating a range of 1 address).
    :param purpose: If supplied, stores a comment in the range object to
        indicate the purpose of this range.
    """
    if isinstance(first, int):
        first = IPAddress(first)
    if second is None:
        second = first
    else:
        if isinstance(second, int):
            second = IPAddress(second)
    iprange = MAASIPRange(inet_ntop(first), inet_ntop(second), purpose=purpose)
    return iprange 
Example #5
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_contains_method(self):
        s = MAASIPSet(
            [
                make_iprange("10.0.0.1", "10.0.0.100"),
                make_iprange("10.0.0.200", "10.0.0.254"),
            ]
        )
        self.assertThat(s, Contains("10.0.0.1"))
        self.assertThat(s, Contains(IPAddress("10.0.0.1")))
        self.assertThat(s, Contains(IPRange("10.0.0.1", "10.0.0.100")))
        self.assertThat(s, Not(Contains(IPRange("10.0.0.1", "10.0.0.101"))))
        self.assertThat(s, Not(Contains("10.0.0.101")))
        self.assertThat(s, Not(Contains("10.0.0.199")))
        self.assertThat(s, Contains(IPRange("10.0.0.200", "10.0.0.254")))
        self.assertThat(s, Not(Contains(IPRange("10.0.0.99", "10.0.0.254"))))
        self.assertThat(s, Not(Contains("10.0.0.255"))) 
Example #6
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_normalizes_range_with_iprange(self):
        addr1 = "10.0.0.1"
        addr2 = IPAddress("10.0.0.2")
        range1 = make_iprange("10.0.0.3", purpose="DNS")
        range2 = IPRange("10.0.0.4", "10.0.0.100")
        s = MAASIPSet([range2, range1, addr1, addr2])
        for item in s:
            self.assertThat(type(item), Equals(MAASIPRange))
        self.assertThat(s, Contains("10.0.0.1"))
        self.assertThat(s, Contains("10.0.0.2"))
        self.assertThat(s, Contains("10.0.0.3"))
        self.assertThat(s, Contains("10.0.0.4"))
        self.assertThat(s, Contains("10.0.0.50"))
        self.assertThat(s, Contains("10.0.0.100"))
        self.assertThat(s, Not(Contains("10.0.0.101")))
        self.assertThat(s, Not(Contains("10.0.0.0"))) 
Example #7
Source File: network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def find(self, search) -> Optional[MAASIPRange]:
        """Searches the list of IPRange objects until it finds the specified
        search parameter, and returns the range it belongs to if found.
        (If the search parameter is a range, returns the result based on
        matching the searching for the range containing the first IP address
        within that range.)
        """
        if isinstance(search, IPRange):
            for item in self.ranges:
                if (
                    item.first <= search.first <= item.last
                    and item.first <= search.last <= item.last
                ):
                    return item
        else:
            addr = IPAddress(search)
            addr = int(addr)
            for item in self.ranges:
                if item.first <= addr <= item.last:
                    return item
        return None 
Example #8
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_excplicitly(self):
        # The other tests in this TestCase rely on
        # get_expected_generate_directives(), which is quite dense. Here
        # we test get_GENERATE_directives() explicitly.
        ip_range = IPRange("192.168.0.55", "192.168.2.128")
        expected_directives = [
            ("55-255", "$.0.168.192.in-addr.arpa.", "192-168-0-$.domain."),
            ("0-255", "$.1.168.192.in-addr.arpa.", "192-168-1-$.domain."),
            ("0-128", "$.2.168.192.in-addr.arpa.", "192-168-2-$.domain."),
        ]
        self.assertItemsEqual(
            expected_directives,
            DNSReverseZoneConfig.get_GENERATE_directives(
                ip_range,
                domain="domain",
                zone_info=DomainInfo(
                    IPNetwork("192.168.0.0/16"), "168.192.in-addr.arpa"
                ),
            ),
        ) 
Example #9
Source File: iprange.py    From wfuzz with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, params):
        BasePayload.__init__(self, params)

        try:
            from netaddr import IPRange
            from netaddr.core import AddrFormatError

            ran = self.params["iprange"].split("-")
            net = IPRange(ran[0], ran[1])
            self.f = iter(net)
            self.__count = net.size
        except ImportError:
            raise FuzzExceptBadInstall("ipnet plugin requires netaddr module. Please install it using pip.")
        except AddrFormatError:
            raise FuzzExceptPluginBadParams("The specified network range has an incorrect format.")
        except IndexError:
            raise FuzzExceptPluginBadParams("The specified network range has an incorrect format.") 
Example #10
Source File: px.py    From px with MIT License 6 votes vote down vote up
def parse_ip_ranges(iprangesconfig):
    ipranges = netaddr.IPSet([])

    iprangessplit = [i.strip() for i in iprangesconfig.split(",")]
    for iprange in iprangessplit:
        if not iprange:
            continue

        try:
            if "-" in iprange:
                spl = iprange.split("-", 1)
                ipns = netaddr.IPRange(spl[0], spl[1])
            elif "*" in iprange:
                ipns = netaddr.IPGlob(iprange)
            else:
                ipns = netaddr.IPNetwork(iprange)
            ipranges.add(ipns)
        except:
            pprint("Bad IP definition: %s" % iprangesconfig)
            sys.exit()
    return ipranges 
Example #11
Source File: blacklist.py    From ws-backend-community with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, blacklist_string):
        """
        Initialize a IPBlacklistEntry object based on the blacklist_string
        argument.
        :param blacklist_string: The string to build an IPBlacklistEntry object
         from.
        :return: None
        """
        self._ip_string = blacklist_string[:blacklist_string.find(",")].strip()
        self._range_name = blacklist_string[blacklist_string.find(",") + 1:].strip()
        if "-" in self._ip_string:
            range_start = self._ip_string[:self._ip_string.find("-")].strip()
            range_end = self._ip_string[self._ip_string.find("-") + 1:].strip()
            self._ip_range = IPRange(range_start, range_end)
        else:
            self._ip_range = IPNetwork(self._ip_string)

    # Static Methods

    # Class Methods

    # Public Methods 
Example #12
Source File: extra.py    From enos with GNU General Public License v3.0 6 votes vote down vote up
def pop_ip(provider_net):
    """Picks an ip from the provider_net
    It will first take ips in the extra_ips if possible.
    extra_ips is a list of isolated ips whereas ips described
    by the [provider_net.start, provider.end] range is a continuous
    list of ips.
    """
    # Construct the pool of ips
    extra_ips = provider_net.get('extra_ips', [])
    if len(extra_ips) > 0:
        ip = extra_ips.pop()
        provider_net['extra_ips'] = extra_ips
        return ip

    ips = list(IPRange(provider_net['start'],
                       provider_net['end']))

    # Get the next ip
    ip = str(ips.pop())

    # Remove this ip from the env
    provider_net['end'] = str(ips.pop())

    return ip 
Example #13
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_finds_partial_intersection(self):
        range_1 = IPRange("10.0.0.1", "10.0.0.128")
        range_2 = IPRange("10.0.0.64", "10.0.0.200")
        intersect = intersect_iprange(range_1, range_2)
        self.expectThat(
            IPAddress(intersect.first), Equals(IPAddress("10.0.0.64"))
        )
        self.expectThat(
            IPAddress(intersect.last), Equals(IPAddress("10.0.0.128"))
        ) 
Example #14
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_returns_true_when_ip_range_is_within_network(self):
        ip_range = IPRange("10.0.0.55", "10.0.255.55")
        ip_network = IPNetwork("10.0.0.0/16")
        self.assertTrue(ip_range_within_network(ip_range, ip_network)) 
Example #15
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_writes_reverse_dns_zone_config_for_small_network(self):
        target_dir = patch_dns_config_path(self)
        domain = factory.make_string()
        ns_host_name = factory.make_name("ns")
        network = IPNetwork("192.168.0.1/26")
        dynamic_network = IPNetwork("192.168.0.1/28")
        dns_zone_config = DNSReverseZoneConfig(
            domain,
            serial=random.randint(1, 100),
            network=network,
            ns_host_name=ns_host_name,
            dynamic_ranges=[
                IPRange(dynamic_network.first, dynamic_network.last)
            ],
        )
        dns_zone_config.write_config()
        reverse_zone_name = "0-26.0.168.192.in-addr.arpa"
        reverse_file_name = "zone.0-26.0.168.192.in-addr.arpa"
        expected_GEN_direct = dns_zone_config.get_GENERATE_directives(
            dynamic_network, domain, DomainInfo(network, reverse_zone_name)
        )
        expected = ContainsAll(
            ["30 IN NS %s." % ns_host_name]
            + [
                "$GENERATE %s %s IN PTR %s"
                % (iterator_values, reverse_dns, hostname)
                for iterator_values, reverse_dns, hostname in expected_GEN_direct
            ]
        )
        self.assertThat(
            os.path.join(target_dir, reverse_file_name),
            FileContains(matcher=expected),
        ) 
Example #16
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_returns_single_entry_for_weird_small_range(self):
        ip_range = IPRange("10.0.0.1", "10.0.0.255")
        domain = factory.make_string()
        directives = DNSReverseZoneConfig.get_GENERATE_directives(
            ip_range,
            domain,
            DomainInfo(IPNetwork("10.0.0.0/24"), "0.0.10.in-addr.arpa"),
        )
        self.expectThat(directives, HasLength(1))

    # generate 2 zones, rather than 1 zone with 2 GENERATEs. 
Example #17
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ignores_networks_that_span_slash_16s(self):
        # If the upper and lower bounds of a range span two /16 networks
        # (but contain between them no more than 65536 addresses),
        # get_GENERATE_directives() will return early
        ip_range = IPRange("10.0.0.55", "10.1.0.54")
        directives = DNSReverseZoneConfig.get_GENERATE_directives(
            ip_range,
            factory.make_string(),
            DomainInfo(IPNetwork("10.0.0.0/15"), "do not care"),
        )
        self.assertEqual([], directives) 
Example #18
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_excplicitly(self):
        # The other tests in this TestCase rely on
        # get_expected_generate_directives(), which is quite dense. Here
        # we test get_GENERATE_directives() explicitly.
        ip_range = IPRange("192.168.0.55", "192.168.2.128")
        expected_directives = [
            ("55-255", "192-168-0-$", "192.168.0.$"),
            ("0-255", "192-168-1-$", "192.168.1.$"),
            ("0-128", "192-168-2-$", "192.168.2.$"),
        ]
        self.assertItemsEqual(
            expected_directives,
            DNSForwardZoneConfig.get_GENERATE_directives(ip_range),
        ) 
Example #19
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ignores_networks_that_span_slash_16s(self):
        # If the upper and lower bounds of a range span two /16 networks
        # (but contain between them no more than 65536 addresses),
        # get_GENERATE_directives() will return early
        ip_range = IPRange("10.0.0.55", "10.1.0.54")
        directives = DNSForwardZoneConfig.get_GENERATE_directives(ip_range)
        self.assertEqual([], directives) 
Example #20
Source File: iprange.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def netaddr_iprange(self):
        return netaddr.IPRange(self.start_ip, self.end_ip) 
Example #21
Source File: discover_nodes.py    From JetPack with Apache License 2.0 5 votes vote down vote up
def ip_set_from_address_range(start, end):
    try:
        start_ip_address = ip_address_from_address(start)
        end_ip_address = ip_address_from_address(end)
    except (NotSupported, ValueError) as e:
        raise ValueError(
            ('invalid IP range: %(start)s-%(end)s (%(message)s)') %
            {
                'start': start,
                'end': end,
                'message': e.message})
    except netaddr.AddrFormatError as e:
        raise ValueError(
            ("invalid IP range: '%(start)s-%(end)s' (%(message)s)") %
            {
                'start': start,
                'end': end,
                'message': e.message})

    if start_ip_address > end_ip_address:
        raise ValueError(
            ('invalid IP range: %(start)s-%(end)s (lower bound IP greater than'
             ' upper bound)') %
            {
                'start': start,
                'end': end})

    ip_range = netaddr.IPRange(start_ip_address, end_ip_address)

    return netaddr.IPSet(ip_range) 
Example #22
Source File: test_zoneconfig.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_writes_reverse_dns_zone_config(self):
        target_dir = patch_dns_config_path(self)
        domain = factory.make_string()
        ns_host_name = factory.make_name("ns")
        network = IPNetwork("192.168.0.1/22")
        dynamic_network = IPNetwork("192.168.0.1/28")
        dns_zone_config = DNSReverseZoneConfig(
            domain,
            serial=random.randint(1, 100),
            network=network,
            ns_host_name=ns_host_name,
            dynamic_ranges=[
                IPRange(dynamic_network.first, dynamic_network.last)
            ],
        )
        dns_zone_config.write_config()
        for sub in range(4):
            reverse_file_name = "zone.%d.168.192.in-addr.arpa" % sub
            expected_GEN_direct = dns_zone_config.get_GENERATE_directives(
                dynamic_network,
                domain,
                DomainInfo(
                    IPNetwork("192.168.%d.0/24" % sub),
                    "%d.168.192.in-addr.arpa" % sub,
                ),
            )
            expected = ContainsAll(
                ["30 IN NS %s." % ns_host_name]
                + [
                    "$GENERATE %s %s IN PTR %s"
                    % (iterator_values, reverse_dns, hostname)
                    for iterator_values, reverse_dns, hostname in expected_GEN_direct
                ]
            )
            self.assertThat(
                os.path.join(target_dir, reverse_file_name),
                FileContains(matcher=expected),
            ) 
Example #23
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_finds_intersection_between_two_ranges(self):
        range_1 = IPRange("10.0.0.1", "10.0.0.255")
        range_2 = IPRange("10.0.0.128", "10.0.0.200")
        intersect = intersect_iprange(range_1, range_2)
        self.expectThat(
            IPAddress(intersect.first), Equals(IPAddress("10.0.0.128"))
        )
        self.expectThat(
            IPAddress(intersect.last), Equals(IPAddress("10.0.0.200"))
        ) 
Example #24
Source File: network.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def network_range(self):
        """
        Get the network range that this Network entry reflects.
        :return: the network range that this Network entry reflects.
        """
        return IPRange(self.start_address, self.end_address) 
Example #25
Source File: network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def ip_range_within_network(ip_range, network):
    """Check that the whole of a given IP range is within a given network."""
    # Make sure that ip_range is an IPRange and not an IPNetwork,
    # otherwise this won't work.
    if isinstance(ip_range, IPNetwork):
        ip_range = IPRange(IPAddress(network.first), IPAddress(network.last))
    return all([intersect_iprange(cidr, network) for cidr in ip_range.cidrs()]) 
Example #26
Source File: network.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def network_range(self):
        """
        Get the network range that this Network entry reflects.
        :return: the network range that this Network entry reflects.
        """
        return IPRange(self.start_address, self.end_address) 
Example #27
Source File: network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, start, end=None, flags=0, purpose=None):
        if purpose is None:
            purpose = set()
        if end is None:
            end = start
        if type(start) == IPRange:
            end = start.last
            start = start.first
        super().__init__(start, end, flags=flags)
        self.flags = flags
        if type(purpose) != set:
            purpose = {purpose}
        self.purpose = purpose 
Example #28
Source File: ARP.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def get_range(self, targets):
        if targets is None:
            return None

        try:
            target_list = []
            for target in targets.split(','):

                if '/' in target:
                    target_list.extend(list(IPNetwork(target)))

                elif '-' in target:
                    start_addr = IPAddress(target.split('-')[0])
                    try:
                        end_addr = IPAddress(target.split('-')[1])
                        ip_range = IPRange(start_addr, end_addr)
                    except AddrFormatError:
                        end_addr = list(start_addr.words)
                        end_addr[-1] = target.split('-')[1]
                        end_addr = IPAddress('.'.join(map(str, end_addr)))
                        ip_range = IPRange(start_addr, end_addr)

                    target_list.extend(list(ip_range))

                else:
                    target_list.append(IPAddress(target))

            return target_list

        except AddrFormatError:
            sys.exit("Specified an invalid IP address/range/network as target") 
Example #29
Source File: nmap.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def get_all_ips(self):
        """
        Get a list that can be iterated over that includes every IP address currently
        configured in this scanner.
        :return: A list that can be iterated over that includes every IP address currently
        configured in this scanner.
        """
        to_return = []
        for address in self.ipv4_addresses:
            to_return.append(IPAddress(address))
        for range_start, range_end in self.ipv4_ranges:
            to_return.append(IPRange(range_start, range_end))
        for network in self.ipv4_networks:
            to_return.append(IPNetwork(network))
        return to_return 
Example #30
Source File: blacklist.py    From ws-backend-community with GNU General Public License v3.0 5 votes vote down vote up
def ip_range(self):
        """
        Get the netaddr object representing the range as described by the
        string used to initialize the IPBlacklistEntry object.
        :return: The netaddr object representing the range as described by the
        string used to initialize the IPBlacklistEntry object. This can be either
        a netaddr.IPRange or netaddr.IPNetwork.
        """
        return self._ip_range