How to use the netaddr.iprange_to_cidrs function in netaddr

To help you get started, we’ve selected a few netaddr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github projectcalico / libcalico / calico_containers / calico_ctl / pool.py View on Github external
ip_range = IPRange(start_ip, end_ip)
    pools = client.get_ip_pools(version)
    for pool in pools:
        pool_net = IPNetwork(pool.cidr)
        # Reject the new ip range if any of the following are true:
        # - The new ip range contains all ips of any existing pool
        # - An existing pool overlaps ips with the start of the new ip range
        # - An existing pool overlaps ips with the end of the new ip range
        if (pool_net in ip_range or
            start_ip in pool_net or
            end_ip in pool_net):
            print "Cannot add range - range conflicts with pool %s" % pool.cidr
            sys.exit(1)

    cidrs = netaddr.iprange_to_cidrs(start_ip, end_ip)
    for ip_net in cidrs:
        new_pool = IPPool(ip_net.cidr, ipip=ipip, masquerade=masquerade)
        client.add_ip_pool(version, new_pool)
github depthsecurity / armory / armory / included / modules / Ingestor.py View on Github external
def process_cidr(self, line, label):
        display("Processing %s" % line)
        if "/" in line:
            created, cidr = self.ScopeCIDR.find_or_create(cidr=line.strip(), label=label)
            if created:
                display_new("Adding %s to scoped CIDRs in database" % line.strip())
                cidr.in_scope = True
                cidr.update()

        elif "-" in line:
            start_ip, end_ip = line.strip().replace(" ", "").split("-")
            if "." not in end_ip:
                end_ip = ".".join(start_ip.split(".")[:3] + [end_ip])

            cidrs = iprange_to_cidrs(start_ip, end_ip)

            for c in cidrs:

                created, cidr = self.ScopeCIDR.find_or_create(cidr=str(c))
                if created:
                    display_new("Adding %s to scoped CIDRs in database" % line.strip())
                    cidr.in_scope = True
                    cidr.update()
github berkgoksel / Elayv / elayv.py View on Github external
with open(sys.argv[2], 'r') as file:
            f = file.read().split('\n')
            ip_list = list(filter(None, f))

    elif (sys.argv[1] == '-W'):
        with open(sys.argv[2], 'r') as file:
            # f = file.read().split('\n')
            # file.read().split('inetnum')
            for line in file:
                if "inetnum" in line:
                    ips = prog_ip.findall(line)
                    startip = ips[0]
                    startip = startip[0] + '.' + startip[1] + '.' + startip[2] + '.' + startip[3]
                    endip = ips[1]
                    endip = endip[0] + '.' + endip[1] + '.' + endip[2] + '.' + endip[3]
                    cidrs = netaddr.iprange_to_cidrs(startip, endip)
                    net2 = ipaddress.ip_network(cidrs[0])
                    for x in net2.hosts():
                        ip_list.append(str(x))

    else:
        print("Invalid arguments!")
        sys.exit(1);

    return ip_list
github zdresearch / OWASP-Nettacker / core / ip.py View on Github external
Args:
        Range: IP range string
        range_temp: range_temp filename
        language: language

    Returns:
        an array of IP range in IPNetwork type
    """
    myranges_now = open(range_temp).read().rsplit()
    if Range not in myranges_now:
        __log_into_file(range_temp, 'a', Range + '\n', language)
        if len(Range.rsplit('.')) is 7 and '-' in Range and '/' not in Range:
            if len(Range.rsplit('-')) is 2:
                start_ip, stop_ip = Range.rsplit('-')
                if isIP(start_ip) and isIP(stop_ip):
                    return iprange_to_cidrs(start_ip, stop_ip)
                else:
                    return []
            else:
                return []
        elif len(Range.rsplit('.')) is 4 and '-' not in Range and '/' in Range:
            return IPNetwork(Range)
        else:
            return []
    else:
        warn(messages(language, 49))
        return []
github xyuanmu / checkiptools / generate_googleip.py View on Github external
def ip_range_to_cidrs():

    ip_lists = []
    ip_lists_2 = []
    ip_range = open('googleip.txt')

    for x in ip_range:
        sline = x.strip().split('-')
        ip_lists.append(sline)

    for ip_line in ip_lists:
        cidrs = netaddr.iprange_to_cidrs(ip_line[0], ip_line[1])
        for k, v in enumerate(cidrs):
            iplist = v
            ip_lists_2.append(iplist)
    #print ip_lists_2

    fd = open('googleip.ip.txt', 'w')
    for ip_cidr in ip_lists_2:
        #print ip_cidr
        fd.write(str(ip_cidr) + "\n")
    fd.close()
github projectcalico / calicoctl / calicoctl / calico_ctl / pool.py View on Github external
ip_range = IPRange(start_ip, end_ip)
    pools = client.get_ip_pools(version)
    for pool in pools:
        pool_net = IPNetwork(pool.cidr)
        # Reject the new ip range if any of the following are true:
        # - The new ip range contains all ips of any existing pool
        # - An existing pool overlaps ips with the start of the new ip range
        # - An existing pool overlaps ips with the end of the new ip range
        if (pool_net in ip_range or
            start_ip in pool_net or
            end_ip in pool_net):
            print "Cannot add range - range conflicts with pool %s" % pool.cidr
            sys.exit(1)

    cidrs = netaddr.iprange_to_cidrs(start_ip, end_ip)
    new_pools = []
    for ip_net in cidrs:
        try:
            new_pools.append(IPPool(ip_net.cidr, ipip=ipip, masquerade=masquerade))
        except InvalidBlockSizeError:
            pool_strings = [str(net) for net in cidrs]
            print "IPv%s ranges are split into pools, with the smallest pool " \
                  "size allowed having a prefix length of /%s. One or more " \
                  "of the generated pools is too small (prefix length is too " \
                  "high).\nRange given: %s - %s\nPools: %s\nNo pools added." % \
                  (version, BLOCK_PREFIXLEN[version], start_ip, end_ip,
                   pool_strings)
            sys.exit(1)
    for new_pool in new_pools:
        client.add_ip_pool(version, new_pool)
github oasis-open / cti-stix-elevator / stix2elevator / convert_cybox.py View on Github external
def handle_inclusive_ip_addresses(add_value, obj1x_id):
    if add_value.condition == 'InclusiveBetween' and isinstance(add_value.value, list):
        x = text_type(netaddr.iprange_to_cidrs(text_type(add_value.value[0]), text_type(add_value.value[1])))
        m = re.match(r".*'(\d+.\d+.\d+.\d+/\d+).*", x)
        if m:
            return m.group(1)
        else:
            warn("Cannot convert range of %s to %s in %s to a CIDR", 501, add_value.value[0], add_value.value[1], obj1x_id)
            return None
    else:
        return text_type(add_value.value)
github duo-labs / neustar2mmdb / preprocess.py View on Github external
def process_row(row, fields):
    res = []
    netblocks = netaddr.iprange_to_cidrs(netaddr.IPAddress(row['start_ip_int']), netaddr.IPAddress(row['end_ip_int']))
    for netblock in netblocks:
        row['netblock'] = netblock
        res.append([row[field] for field in fields])

    return res