Python netaddr.IPRange() Examples

The following are 30 code examples for showing how to use netaddr.IPRange(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module netaddr , or try the search function .

Example 1
Project: px   Author: genotrance   File: px.py    License: 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 2
Project: clapper   Author: rthallisey   File: ip_range.py    License: 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
Project: clapper   Author: rthallisey   File: ip_range.py    License: 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
Project: enos   Author: BeyondTheClouds   File: extra.py    License: 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 5
Project: wfuzz   Author: xmendez   File: iprange.py    License: 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 6
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 7
Project: ws-backend-community   Author: lavalamp-   File: blacklist.py    License: 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 8
Project: maas   Author: maas   File: network.py    License: 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 9
Project: maas   Author: maas   File: network.py    License: 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 10
Project: maas   Author: maas   File: test_network.py    License: 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 11
Project: maas   Author: maas   File: test_network.py    License: 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 12
Project: maas   Author: maas   File: test_zoneconfig.py    License: 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 13
Project: JetPack   Author: dsp-jetpack   File: discover_nodes.py    License: 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 14
Project: lsassy   Author: Hackndo   File: utils.py    License: MIT License 5 votes vote down vote up
def parse_targets(target):
    if '-' in target:
        ip_range = target.split('-')
        try:
            t = IPRange(ip_range[0], ip_range[1])
        except AddrFormatError:
            try:
                start_ip = IPAddress(ip_range[0])

                start_ip_words = list(start_ip.words)
                start_ip_words[-1] = ip_range[1]
                start_ip_words = [str(v) for v in start_ip_words]

                end_ip = IPAddress('.'.join(start_ip_words))

                t = IPRange(start_ip, end_ip)
            except AddrFormatError:
                t = target
    else:
        try:
            t = IPNetwork(target)
        except AddrFormatError:
            t = target
    if type(t) == IPNetwork or type(t) == IPRange:
        return list(t)
    else:
        return [t.strip()] 
Example 15
Project: minemeld-core   Author: PaloAltoNetworks   File: feedredis.py    License: Apache License 2.0 5 votes vote down vote up
def _translate_ip_ranges(indicator, value=None):
    if value is not None and value['type'] != 'IPv4':
        return [indicator]

    try:
        ip_range = IPRange(*indicator.split('-', 1))

    except (AddrFormatError, ValueError, TypeError):
        return [indicator]

    return [str(x) if x.size != 1 else str(x.network) for x in ip_range.cidrs()] 
Example 16
Project: minemeld-core   Author: PaloAltoNetworks   File: taxii.py    License: Apache License 2.0 5 votes vote down vote up
def _stix_ip_observable(namespace, indicator, value):
    category = cybox.objects.address_object.Address.CAT_IPV4
    if value['type'] == 'IPv6':
        category = cybox.objects.address_object.Address.CAT_IPV6

    indicators = [indicator]
    if '-' in indicator:
        # looks like an IP Range, let's try to make it a CIDR
        a1, a2 = indicator.split('-', 1)
        if a1 == a2:
            # same IP
            indicators = [a1]
        else:
            # use netaddr builtin algo to summarize range into CIDR
            iprange = netaddr.IPRange(a1, a2)
            cidrs = iprange.cidrs()
            indicators = map(str, cidrs)

    observables = []
    for i in indicators:
        id_ = '{}:observable-{}'.format(
            namespace,
            uuid.uuid4()
        )

        ao = cybox.objects.address_object.Address(
            address_value=i,
            category=category
        )

        o = cybox.core.Observable(
            title='{}: {}'.format(value['type'], i),
            id_=id_,
            item=ao
        )

        observables.append(o)

    return observables 
Example 17
Project: a10-neutron-lbaas   Author: a10networks   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def find_unused_ip(ip_range_begin, ip_range_end, ips_in_use):
        candidate = None

        in_range = ipset(iprange(ip_range_begin, ip_range_end))
        in_use = ipset(ips_in_use)

        try:
            candidate = str(ipaddr((in_range - in_use).pop()))
        except Exception:
            LOG.error("Could not allocate IP address for range:{0}-{1}".format(
                ip_range_begin, ip_range_end))
        finally:
            return candidate 
Example 18
Project: Interlace   Author: codingo   File: input.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_ips_from_range(ip_range):
        ips = set()
        ip_range = ip_range.split("-")

        # parsing the above structure into an array and then making into an IP address with the end value
        end_ip = ".".join(ip_range[0].split(".")[0:-1]) + "." + ip_range[1]

        # creating an IPRange object to get all IPs in between
        range_obj = IPRange(ip_range[0], end_ip)

        for ip in range_obj:
            ips.add(str(ip))

        return ips 
Example 19
Project: utilitybelt   Author: yolothreat   File: utilitybelt.py    License: MIT License 5 votes vote down vote up
def ip_between(ip, start, finish):
    """Checks to see if IP is between start and finish"""

    if is_IPv4Address(ip) and is_IPv4Address(start) and is_IPv4Address(finish):
        return IPAddress(ip) in IPRange(start, finish)
    else:
        return False 
Example 20
Project: pythem   Author: m4n3dw0lf   File: scanner.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_range(self, targets):
        if targets is None:
            return None
        if targets is not 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 Exception as e:
                try:
                    target = socket.gethostbyname(self.targets)
                    target_list.append(target)
                    return target_list
                except:
                    print "[!] Exception caught: {}".format(e) 
Example 21
Project: pythem   Author: m4n3dw0lf   File: arpoisoner.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_range(self, targets):
        if targets is None:
            print "[!] IP address/range was not specified, will intercept only gateway requests and not replies."
            return None
        try:
            target_list = []
            for target in targets.split(','):
                if '/' in target:
                    self.range = True
                    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("[!] Select a valid IP address/range as target") 
Example 22
Project: pytos   Author: Tufin   File: rules.py    License: Apache License 2.0 5 votes vote down vote up
def as_netaddr_obj(self):
        return netaddr.IPRange(self.first_ip, self.last_ip, flags=netaddr.ZEROFILL) 
Example 23
Project: pytos   Author: Tufin   File: rules.py    License: Apache License 2.0 5 votes vote down vote up
def as_netaddr_obj(self):
        if self.src.from_ == self.src.to:
            src = netaddr.IPNetwork(self.src.from_, flags=netaddr.ZEROFILL)
        else:
            src = netaddr.IPRange(self.src.from_, self.src.to, flags=netaddr.ZEROFILL)
        return src 
Example 24
Project: pytos   Author: Tufin   File: rest.py    License: Apache License 2.0 5 votes vote down vote up
def as_netaddr_obj(self):
        return netaddr.IPRange(self.first_ip, self.last_ip) 
Example 25
Project: combine   Author: mlsecproject   File: winnower.py    License: GNU General Public License v3.0 5 votes vote down vote up
def load_gi_org(filename):
    with open(filename, 'rb') as f:
        org_reader = csv.DictReader(f, fieldnames=['start', 'end', 'org'])
        for row in org_reader:
            gi_org[row['start']] = (IPRange(row['start'], row['end']), unicode(row['org'], errors='replace'))

    return gi_org 
Example 26
Project: clapper   Author: rthallisey   File: validate_network_environment.py    License: Apache License 2.0 5 votes vote down vote up
def ranges_conflicting_with_ip(ip_address, ip_ranges):
    """Check for all conflicts of the IP address conflicts.

    This takes a single IP address and a list of `(pool_name,
    netenv.IPRange)`s.

    We return all ranges that the IP address conflicts with. This is to
    improve the final error messages.
    """
    return [(pool_name, ip_range) for (pool_name, ip_range) in ip_ranges
            if ip_address in ip_range] 
Example 27
Project: clapper   Author: rthallisey   File: validate_network_environment.py    License: Apache License 2.0 5 votes vote down vote up
def ranges_conflicting_with_ip(ip_address, ip_ranges):
    """Check for all conflicts of the IP address conflicts.

    This takes a single IP address and a list of `(pool_name,
    netenv.IPRange)`s.

    We return all ranges that the IP address conflicts with. This is to
    improve the final error messages.
    """
    return [(pool_name, ip_range) for (pool_name, ip_range) in ip_ranges
            if ip_address in ip_range] 
Example 28
Project: piSociEty   Author: paranoidninja   File: ARP.py    License: 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
Project: tripleo-validations   Author: openstack   File: network_environment.py    License: Apache License 2.0 5 votes vote down vote up
def ranges_conflicting_with_ip(ip_address, ip_ranges):
    """Check for all conflicts of the IP address conflicts.

    This takes a single IP address and a list of `(pool_name,
    netenv.IPRange)`s.

    We return all ranges that the IP address conflicts with. This is to
    improve the final error messages.
    """
    return [(pool_name, ip_range) for (pool_name, ip_range) in ip_ranges
            if ip_address in ip_range] 
Example 30
Project: tripleo-validations   Author: openstack   File: ip_range.py    License: Apache License 2.0 5 votes vote down vote up
def check_IP_range(start, end, min_size):
    '''Compare IP range with minimum size'''

    errors = []
    iprange = netaddr.IPRange(start, end)

    if len(iprange) < min_size:
        errors = [
            'The IP range {} - {} contains {} addresses.'.format(
                start, end, len(iprange)),
            'This might not be enough for the deployment or later scaling.'
        ]

    return errors