Python ipaddr.IPNetwork() Examples

The following are 19 code examples of ipaddr.IPNetwork(). 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 ipaddr , or try the search function .
Example #1
Source File: geolite2legacy.py    From geolite2legacy with MIT License 6 votes vote down vote up
def gen_nets(self, locations, infile):
        for row in csv.DictReader(infile):
            location = locations.get(row['geoname_id'])
            if location is None:
                continue

            nets = [ipaddr.IPNetwork(row['network'])]
            country_iso_code = location['country_iso_code'] or location['continent_code']
            fips_code = geoname2fips.get(location['geoname_id'])
            if fips_code is None:
                logging.debug('Missing fips-10-4 for {}'.format(location['subdivision_1_name']))
                fips_code = '00'
            else:
                logging.debug('fips-10-4 for {} is {}'.format(location['subdivision_1_name'], fips_code))

            yield nets, (country_iso_code,
                         serialize_text(fips_code),  # region
                         serialize_text(decode_text(location['city_name'])),
                         serialize_text(row['postal_code']),
                         row['latitude'],
                         row['longitude'],
                         location['metro_code'],
                         '')  # area_code 
Example #2
Source File: dosinfo.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def Validate(self, value, unused_key=None):
    """Validates a subnet."""
    if value is None:
      raise validation.MissingAttribute('subnet must be specified')
    if not isinstance(value, basestring):
      raise validation.ValidationError('subnet must be a string, not \'%r\'' %
                                       type(value))
    try:
      ipaddr.IPNetwork(value)
    except ValueError:
      raise validation.ValidationError('%s is not a valid IPv4 or IPv6 subnet' %
                                       value)


    parts = value.split('/')
    if len(parts) == 2 and not re.match('^[0-9]+$', parts[1]):
      raise validation.ValidationError('Prefix length of subnet %s must be an '
                                       'integer (quad-dotted masks are not '
                                       'supported)' % value)

    return value 
Example #3
Source File: webservicescanner.py    From WebServiceScanner with Apache License 2.0 6 votes vote down vote up
def main():
    if len(sys.argv) != 2:
        print 'Usage: python webscan.py 192.168.1.1/24'
    else:
        time_start = time.time()
        threads = []
        thread_count = 200        #线程数
        queue = Queue.Queue()
        cidrip = sys.argv[1]      #接收输入IP段
        ips = ipaddr.IPNetwork(cidrip)

        for ip in ips:
            queue.put(ip)

        for i in xrange(thread_count):
            threads.append(PortScan(queue))

        for t in threads:
            t.start()

        for t in threads:
            t.join()
        print 'ALL Finished, Running Time:' + str(time.time() - time_start) 
Example #4
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def nextAvailableCIDR(self, subnets, network):
        """
        Try to aloccate
        :param subnets:
        :param network:
        :return:
        """

        if not subnets:
            subnet = list(NETADDR(network.network).subnet(int(network.subnet_mask)))[0]
            return str(subnet)

        subnet = NETADDR(subnets.latest('id').network).next()
        if ipaddr.IPNetwork(subnet).overlaps(ipaddr.IPNetwork(network.network)):
            return str(subnet)

        return self.searchNextAvailableCIDR(subnets) 
Example #5
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def check_cidr(self, environment, network):
        """
        check if network is a subnet of the father environment
        :param environment: environment id
        :param network: environment cidr
        :return: boolean
        """

        if environment.father_environment:
            id_env_father = environment.father_environment.id
        else:
            return True

        cidr_env_father = self.get(env_id=id_env_father)

        for cidr in cidr_env_father:
            if ipaddr.IPNetwork(network).overlaps(ipaddr.IPNetwork(cidr.network)):
                return True

        return False 
Example #6
Source File: cluster.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def load_cluster_networks(self):
        self.cluster_net = None
        self.public_net = None

        osd = self.get_alive_osd()
        if osd is not None:
            cluster_net_str = osd.config.get('cluster_network')
            if cluster_net_str is not None and cluster_net_str != "":
                self.cluster_net = IPNetwork(cluster_net_str)

            public_net_str = osd.config.get('public_network', None)
            if public_net_str is not None and public_net_str != "":
                self.public_net = IPNetwork(public_net_str) 
Example #7
Source File: vlan.py    From iSDX with Apache License 2.0 5 votes vote down vote up
def __init__(self, vid, conf=None):
        if conf is None:
            conf = {}
        self.vid = vid
        self.tagged = []
        self.untagged = []
        self.name = conf.setdefault('name', str(vid))
        self.description = conf.setdefault('description', self.name)
        self.controller_ips = conf.setdefault('controller_ips', [])
        if self.controller_ips:
            self.controller_ips = [
                ipaddr.IPNetwork(ip) for ip in self.controller_ips]
        self.unicast_flood = conf.setdefault('unicast_flood', True)
        self.routes = conf.setdefault('routes', {})
        self.ipv4_routes = {}
        self.ipv6_routes = {}
        if self.routes:
            self.routes = [route['route'] for route in self.routes]
            for route in self.routes:
                ip_gw = ipaddr.IPAddress(route['ip_gw'])
                ip_dst = ipaddr.IPNetwork(route['ip_dst'])
                assert(ip_gw.version == ip_dst.version)
                if ip_gw.version == 4:
                    self.ipv4_routes[ip_dst] = ip_gw
                else:
                    self.ipv6_routes[ip_dst] = ip_gw
        self.arp_cache = {}
        self.nd_cache = {}
        self.max_hosts = conf.setdefault('max_hosts', None)
        self.host_cache = {} 
Example #8
Source File: allscanner.py    From Allscanner with MIT License 5 votes vote down vote up
def main():

    print ''
    logo_encode = 'ICAgIF9fXyAgICBfX19fX19fX18gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgLyAgIHwgIC8gLyAvIF9fXy9fX19fX19fX19fX19fX18gIF9fX18gIF9fXyAgX19fX18KICAvIC98IHwgLyAvIC9cX18gXC8gX19fLyBfXyAgLyBfXyBcLyBfXyBcLyBfIFwvIF9fXy8KIC8gX19fIHwvIC8gL19fXy8gLyAvX18vIC9fLyAvIC8gLyAvIC8gLyAvICBfXy8gLyAgICAKL18vICB8Xy9fL18vL19fX18vXF9fXy9cX19fXy9fLyAvXy9fLyAvXy9cX19fL18v='
    logo = base64.b64decode(logo_encode)
    print logo + '\n\n'
    print 'github:https://github.com/aedoo/' + '\n\n'

    parser = argparse.ArgumentParser()
    parser.add_argument('-i', dest='cidr_ip', help='IP segment like 192.168.1.1/16 contains 65536 IP.')
    parser.add_argument('-t', dest='thread_number', type=int, default=100, help='Setting the number of threads')
    args = parser.parse_args()

    print ''

    IP_Duan = str(args.cidr_ip)

    try:
        IPs = ipaddr.IPNetwork(IP_Duan)
        thread_number = args.thread_number

        threads = []
        queue = Queue.Queue()

        for ip in IPs:
            queue.put(str(ip))

        for i in xrange(thread_number):
            threads.append(AllScanner(queue))

        for t in threads:
            t.start()
        for t in threads:
            t.join()

    except Exception:
        parser.print_help() 
Example #9
Source File: dos_xml_parser.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _ValidateEntry(self, entry):
    if not entry.subnet:
      return MISSING_SUBNET
    try:
      ipaddr.IPNetwork(entry.subnet)
    except ValueError:
      return BAD_IPV_SUBNET % entry.subnet
    parts = entry.subnet.split('/')
    if len(parts) == 2 and not re.match('^[0-9]+$', parts[1]):
      return BAD_PREFIX_LENGTH % entry.subnet 
Example #10
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def post(self, env_cidr):

        try:
            if env_cidr.get('id'):
                self.id = env_cidr.get('id')
            self.network = env_cidr.get('network')
            self.network_first_ip = env_cidr.get('network_first_ip')
            self.network_last_ip = env_cidr.get('network_last_ip')
            self.network_mask = env_cidr.get('network_mask')
            self.ip_version = env_cidr.get('ip_version')
            self.subnet_mask = env_cidr.get('subnet_mask')

            if not self.check_prefix(self.network, self.subnet_mask):
                raise CIDRErrorV3("The prefix %s is not valid for the network %s" % (self.subnet_mask, self.network))

            objects = EnvCIDR.objects.filter(id_env=int(env_cidr.get('environment')))
            for obj in objects:
                if ipaddr.IPNetwork(obj.network).overlaps(ipaddr.IPNetwork(self.network)):
                    raise CIDRErrorV3("%s overlaps %s" % (self.network, obj.network))

            environment = Ambiente().get_by_pk(int(env_cidr.get('environment')))
            self.id_env = environment

            self.id_network_type = TipoRede().get_by_pk(int(env_cidr.get('network_type')))

            self.save()
        except Exception as e:
            raise CIDRErrorV3(e)

        return self.id 
Example #11
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def searchNextAvailableCIDR(self, subnets):
        """
        Method that search next availacle cidr.
        :param subnets: all subnets of environment.
        :return: available subnet
        """
        log.debug("searchNextAvailableCIDR")

        for idx, _ in enumerate(subnets):
            if int(subnets[idx].network_last_ip) + 1 is not int(subnets[idx+1].network_first_ip):
                subnet = subnets[idx].network
                new_subnet = NETADDR(subnet).next()
                if not ipaddr.IPNetwork(new_subnet).overlaps(ipaddr.IPNetwork(subnets[idx+1].network)):
                    return str(new_subnet)
        return "" 
Example #12
Source File: models.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def check_prefix(self, network_address, subnet_mask):
        """
        check if subnet mask is correct, based on network mask.

        :param network_address: environment cidr
        :param subnet_mask: environment cidr subnet mask
        :return: boolean
        """

        network = ipaddr.IPNetwork(network_address)

        return True if int(network.prefixlen) <= int(subnet_mask) else False 
Example #13
Source File: utils.py    From irrexplorer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def classifySearchString(data):

    data = data.strip()

    asn = None
    try:
        asn = int(data)
    except ValueError:
        pass
    if asn:
        if asn < 1:
            raise ValueError('Invalid as number (negative or zero)')
        return ASNumber(asn)

    if data.upper().startswith('AS-'):
        return ASMacro(data.upper()) # as macros are always uppcase

    if data.upper().startswith('AS'):
        try:
            return ASNumber(int(data[2:]))
        except ValueError:
            return ASMacro(data)

    try:
        ipaddr.IPNetwork(data)
        return Prefix(data)
    except ValueError:
        pass

    raise ValueError('Cannot classify %s' % data) 
Example #14
Source File: acehttp.py    From HTTPAceProxy with GNU General Public License v3.0 5 votes vote down vote up
def checkFirewall(clientip):
    try: clientinrange = any([IPAddress(clientip) in IPNetwork(i) for i in AceConfig.firewallnetranges])
    except: logger.error('Check firewall netranges settings !'); return False
    return not ((AceConfig.firewallblacklistmode and clientinrange) or (not AceConfig.firewallblacklistmode and not clientinrange)) 
Example #15
Source File: sort_ranges.py    From armory with GNU General Public License v3.0 5 votes vote down vote up
def merge_ranges(ranges):
    range_data = [[ipaddr.IPNetwork(r).numhosts, ipaddr.IPNetwork(r)] for r in ranges]
    ranges = [r[1] for r in sorted(range_data)[::-1]]
    unique_ranges = [str(r) for r in sort_ranges(ranges)]

    return unique_ranges 
Example #16
Source File: geolite2legacy.py    From geolite2legacy with MIT License 5 votes vote down vote up
def gen_nets(self, locations, infile):
        for row in csv.DictReader(infile):
            location = locations.get(row['geoname_id'])
            if location is None:
                continue

            nets = [ipaddr.IPNetwork(row['network'])]
            country_iso_code = location['country_iso_code'] or location['continent_code']
            yield nets, (country_iso_code,) 
Example #17
Source File: geolite2legacy.py    From geolite2legacy with MIT License 5 votes vote down vote up
def gen_nets(self, locations, infile):
        for row in csv.DictReader(infile):
            nets = [ipaddr.IPNetwork(row['network'])]
            org = decode_text(row['autonomous_system_organization'])
            asn = row['autonomous_system_number']
            entry = u'AS{} {}'.format(asn, org)
            yield nets, (serialize_text(entry),) 
Example #18
Source File: bgpupdate.py    From irrexplorer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def updateBGP(source_url, db):

    logging.info('Updating BGP information')

    source_routes = set()

    # get the bgp routes
    for line in urllib2.urlopen(source_url):
        route, asn = line.strip().split(' ')
        source_routes.add( (route, int(asn)) )

    fltrd_source_routes = set()
    for route, asn in source_routes:
        try:
            route_obj = ipaddr.IPNetwork(route)
        except ValueError:
            logging.error('Invalid route in BGP feed: %s' % route)
            continue

        # block router2router linknets / small blocks
        if route_obj.version == 4 and route_obj.prefixlen >= 29:
            continue
        if route_obj.version == 6 and route_obj.prefixlen >= 124:
            continue

        fltrd_source_routes.add((route, int(asn)))

    logging.info('BGP table fetched and table build, %i routes' % (len(source_routes)))

    # then the database routes
    db_routes = set()
    bgp_rows = db.query_source('bgp')
    logging.info('Got database entries, %i routes' % len(bgp_rows))

    for route, asn in bgp_rows:
        db_routes.add((route, int(asn)))

    # calculate the diff, intersection is just for logging
    routes_is = fltrd_source_routes & db_routes
    deprecated_routes = db_routes - fltrd_source_routes
    new_routes = fltrd_source_routes - db_routes

    logging.info('Routes: %i unchanged / %i deprecated / %i new' % (len(routes_is), len(deprecated_routes), len(new_routes)))

    # create + send update statements
    cur = db._get_cursor()

    for route, asn in deprecated_routes:
        cur.execute(DELETE_STM, (route, asn) )

    for route, asn in new_routes:
        cur.execute(INSERT_STM, (route, asn) )

    db.conn.commit()
    cur.close() # so it doesn't linger while sleeping

    logging.info('BPG update commit done and cursor closed') 
Example #19
Source File: spf.py    From mailin with MIT License 4 votes vote down vote up
def cidrmatch(self, ipaddrs, n):
        """Match connect IP against a CIDR network of other IP addresses.

        Examples:
        >>> c = query(s='strong-bad@email.example.com',
        ...           h='mx.example.org', i='192.0.2.3')
        >>> c.p = 'mx.example.org'
        >>> c.r = 'example.com'

        >>> c.cidrmatch(['192.0.2.3'],32)
        True
        >>> c.cidrmatch(['192.0.2.2'],32)
        False
        >>> c.cidrmatch(['192.0.2.2'],31)
        True

        >>> six = query(s='strong-bad@email.example.com',
        ...           h='mx.example.org', i='2001:0db8:0:0:0:0:0:0001')
        >>> six.p = 'mx.example.org'
        >>> six.r = 'example.com'

        >>> six.cidrmatch(['2001:0DB8::'],127)
        True
        >>> six.cidrmatch(['2001:0DB8::'],128)
        False
        >>> six.cidrmatch(['2001:0DB8:0:0:0:0:0:0001'],128)
        True
        """
        try:
            for netwrk in [ipaddress.ip_network(ip) for ip in ipaddrs]:
                network = netwrk.supernet(new_prefix=n)
                if isinstance(self.iplist, bool):
                    if network.__contains__(self.ipaddr):
                        return True
                else:
                    if n < self.cidrmax:
                        self.iplist.append(network)
                    else:
                        self.iplist.append(network.ip)
        except AttributeError:
            for netwrk in [ipaddress.IPNetwork(ip,strict=False) for ip in ipaddrs]:
                network = netwrk.supernet(new_prefix=n)
                if isinstance(self.iplist, bool):
                    if network.__contains__(self.ipaddr):
                        return True
                else:
                    if n < self.cidrmax:
                        self.iplist.append(network)
                    else:
                        self.iplist.append(network.ip)
        return False