当前位置: 首页>>代码示例>>Python>>正文


Python IPNetwork.subnet方法代码示例

本文整理汇总了Python中netaddr.IPNetwork.subnet方法的典型用法代码示例。如果您正苦于以下问题:Python IPNetwork.subnet方法的具体用法?Python IPNetwork.subnet怎么用?Python IPNetwork.subnet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在netaddr.IPNetwork的用法示例。


在下文中一共展示了IPNetwork.subnet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _create_subnets

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
    def _create_subnets(self):
        logging.debug("creating subnets")
        zones = self.vpc.vpc.connection.get_all_zones()
        logging.debug("zones: %s", zones)
        # We'll need to split each subnet into smaller ones, one per zone
        # offset is how much we need to add to cidr divisor to create at least
        # that len(zone) subnets
        zone_cidr_offset = ceil(log(len(zones), 2))
        logging.debug("zone_offset: %s", zone_cidr_offset)

        network_cidr = IPNetwork(self.vpc.get_config("{0}_cidr".format(self.name)))
        zone_cidrs = network_cidr.subnet(
            int(network_cidr.prefixlen + zone_cidr_offset)
        )

        subnets = []
        for zone, cidr in zip(zones, zone_cidrs):
            logging.debug("%s %s", zone, cidr)
            subnet = self.vpc.vpc.connection.create_subnet(self.vpc.vpc.id, cidr, zone.name)
            self.vpc.vpc.connection.associate_route_table(self.route_table.id, subnet.id)
            self._tag_resource(subnet, zone.name)
            subnets.append(subnet)
            logging.debug("%s subnet: %s", self.name, subnet)

        return subnets
开发者ID:Angakkuit,项目名称:asiaq-aws,代码行数:27,代码来源:disco_metanetwork.py

示例2: allocateInterconnect

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
    def allocateInterconnect(self, interConnectPrefix, spines, leafs):
        numOfIpsPerInterconnect = 2
        numOfSubnets = len(spines) * len(leafs)
        # no need to add +2 for network and broadcast, as junos supports /31
        # TODO: it should be configurable and come from property file
        bitsPerSubnet = int(math.ceil(math.log(numOfIpsPerInterconnect, 2)))    # value is 1  
        cidrForEachSubnet = 32 - bitsPerSubnet  # value is 31 as junos supports /31

        numOfIps = (numOfSubnets * (numOfIpsPerInterconnect)) # no need to add +2 for network and broadcast
        numOfBits = int(math.ceil(math.log(numOfIps, 2))) 
        cidr = 32 - numOfBits
        interconnectBlock = IPNetwork(interConnectPrefix + "/" + str(cidr))
        interconnectSubnets = list(interconnectBlock.subnet(cidrForEachSubnet))

        interfaces = [] 
        spines[0].pod.allocatedInterConnectBlock = str(interconnectBlock.cidr)

        for spine in spines:
            ifdsHasPeer = self.dao.Session().query(InterfaceDefinition).filter(InterfaceDefinition.device_id == spine.id).filter(InterfaceDefinition.peer != None).order_by(InterfaceDefinition.name_order_num).all()
            for spineIfdHasPeer in ifdsHasPeer:
                subnet =  interconnectSubnets.pop(0)
                ips = list(subnet)
                
                spineEndIfl= InterfaceLogical(spineIfdHasPeer.name + '.0', spine, str(ips.pop(0)) + '/' + str(cidrForEachSubnet))
                spineIfdHasPeer.layerAboves.append(spineEndIfl)
                interfaces.append(spineEndIfl)
                
                leafEndIfd = spineIfdHasPeer.peer
                leafEndIfl= InterfaceLogical(leafEndIfd.name + '.0', leafEndIfd.device, str(ips.pop(0)) + '/' + str(cidrForEachSubnet))
                leafEndIfd.layerAboves.append(leafEndIfl)
                interfaces.append(leafEndIfl)
        self.dao.createObjects(interfaces)
开发者ID:bgp44,项目名称:juniper,代码行数:34,代码来源:l3Clos.py

示例3: split_subnets

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def split_subnets(cidr, split):
    """
    Finds the nearest power of two to the number of desired subnets,
    Splits a CIDR into that many sub CIDRs, and returns the array.

    :param cidr: CIDR for entire range
    :type cidr: str.
    :param split: Number to split into
    :type split: int.
    :raises: :class:`pmcf.exceptions.PropertyException`
    :returns: list.
    """

    # Find the next closest power of two to a number
    # For 3, return 4, for 5 return 8

    if split == 1:
        return [cidr]

    power = 0
    while split > 0:
        split >>= 1
        power += 1

    try:
        ipaddr = IPNetwork(cidr)
        prefix = ipaddr.prefixlen
        newprefix = prefix + power
        return list(ipaddr.subnet(newprefix))
    except Exception, exc:
        raise PropertyException(str(exc))
开发者ID:pikselpalette,项目名称:pmcf,代码行数:33,代码来源:__init__.py

示例4: create_address_pools

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def create_address_pools(interfaceorder, networks_pools):
    address_pools = {
        iname: {
            'net': ':'.join(networks_pools[iname]),
            'params': {
                'ip_reserved': {
                    # Gateway will be used for configure OpenStack networks
                    'gateway': 1,
                    # l2_network_device will be used for configure local bridge
                    'l2_network_device': 1,
                },
                'ip_ranges': {
                    'default': [2, -2],
                },
            },
        } for iname in interfaceorder
    }

    if 'public' in interfaceorder:
        # Put floating IP range for public network
        default_pool_name = 'default'
        floating_pool_name = 'floating'

        # Take a first subnet with necessary size and calculate the size
        net = IPNetwork(networks_pools['public'][0])
        new_prefix = int(networks_pools['public'][1])
        subnet = next(net.subnet(prefixlen=new_prefix))
        network_size = subnet.size

        address_pools['public']['params']['ip_ranges'][default_pool_name] = [
            2, network_size // 2 - 1]
        address_pools['public']['params']['ip_ranges'][floating_pool_name] = [
            network_size // 2, -2]

    return address_pools
开发者ID:loles,项目名称:fuel-devops,代码行数:37,代码来源:templates.py

示例5: test_extended_cidr_merge

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def test_extended_cidr_merge():

    orig_cidr_ipv4 = IPNetwork('192.0.2.0/23')
    orig_cidr_ipv6 = IPNetwork('::192.0.2.0/120')

    cidr_subnets = [str(c) for c in orig_cidr_ipv4.subnet(28)] + \
                   list(orig_cidr_ipv4.subnet(28)) + \
                   [str(c) for c in orig_cidr_ipv6.subnet(124)] + \
                   list(orig_cidr_ipv6.subnet(124)) + \
                   ['192.0.2.1/32', '192.0.2.128/25', '::192.0.2.92/128']

    random.shuffle(cidr_subnets)

    merged_cidrs = cidr_merge(cidr_subnets)

    assert merged_cidrs == [IPNetwork('192.0.2.0/23'), IPNetwork('::192.0.2.0/120')]
    assert merged_cidrs == [orig_cidr_ipv4, orig_cidr_ipv6]
开发者ID:drkjam,项目名称:netaddr,代码行数:19,代码来源:test_cidr_v4.py

示例6: calculate_subnet

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def calculate_subnet(vpc_net: IPNetwork, _type: str, az_index: int):
    """
    >>> calculate_subnet(IPNetwork('10.0.0.0/16'), 'dmz', 0)
    IPNetwork('10.0.0.0/21')

    >>> calculate_subnet(IPNetwork('10.0.0.0/16'), 'internal', 0)
    IPNetwork('10.0.128.0/20')

    >>> calculate_subnet(IPNetwork('10.0.0.0/19'), 'dmz', 0)
    IPNetwork('10.0.0.0/24')

    >>> calculate_subnet(IPNetwork('10.0.0.0/19'), 'dmz', 1)
    IPNetwork('10.0.1.0/24')

    >>> calculate_subnet(IPNetwork('10.0.0.0/18'), 'dmz', 1)
    IPNetwork('10.0.2.0/23')

    >>> calculate_subnet(IPNetwork('10.0.0.0/19'), 'internal', 0)
    IPNetwork('10.0.16.0/23')

    >>> calculate_subnet(IPNetwork('10.0.0.0/19'), 'internal', 1)
    IPNetwork('10.0.18.0/23')

    >>> calculate_subnet(IPNetwork('10.0.0.0/18'), 'internal', 1)
    IPNetwork('10.0.36.0/22')

    >>> calculate_subnet(IPNetwork('10.0.0.0/28'), 'internal', 1)
    IPNetwork('10.0.0.9/32')

    >>> calculate_subnet(IPNetwork('10.0.0.0/30'), 'internal', 1)
    Traceback (most recent call last):
        ...
    netaddr.core.AddrFormatError: invalid IPNetwork 10.0.0.2/34

    >>> calculate_subnet(IPNetwork('10.0.0.0/64'), 'internal', 1)
    Traceback (most recent call last):
        ...
    netaddr.core.AddrFormatError: invalid IPNetwork 10.0.0.0/64
    """
    if _type == "dmz":
        networks = list(vpc_net.subnet(vpc_net.prefixlen + 5))
    else:
        # use the "upper half" of the /16 network for the internal/private subnets
        networks = list(list(vpc_net.subnet(vpc_net.prefixlen + 1))[1].subnet(vpc_net.prefixlen + 4))
    return networks[az_index]
开发者ID:achim,项目名称:sevenseconds,代码行数:47,代码来源:aws.py

示例7: split_network

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def split_network(request):

    try:
        network = IPNetwork(request.GET['network'])
    except (KeyError, AddrFormatError):
        return HttpResponseBadRequest()

    return render(request, 'pammy/split_network.html', {
        'networks': network.subnet(network.prefixlen + 1),
    })
开发者ID:ocadotechnology,项目名称:pammy,代码行数:12,代码来源:ui.py

示例8: is_cidr_reserved

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def is_cidr_reserved(cidr, vpccidr):
    """ Check if CIDR is in the first 2 x /22 in the VPC Range """
    cidr = str(cidr)
    vpc = IPNetwork(vpccidr)
    reserved1 = list(vpc.subnet(22))[0]
    reserved2 = list(vpc.subnet(22))[1]

    if reserved1 == IPNetwork(cidr).supernet(22)[0] or reserved2 == IPNetwork(cidr).supernet(22)[0]:
        return True
    return False
开发者ID:bcosta12,项目名称:AdvancedCloudFormation,代码行数:12,代码来源:autosubnet.py

示例9: create_networks

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
    def create_networks(self, nw_group):
        '''
        Method for creation of networks for network group.

        :param nw_group: NetworkGroup object.
        :type  nw_group: NetworkGroup
        :returns: None
        '''
        fixnet = IPNetwork(nw_group.cidr)
        subnet_bits = int(math.ceil(math.log(nw_group.network_size, 2)))
        logger.debug("Specified network size requires %s bits", subnet_bits)
        subnets = list(fixnet.subnet(32 - subnet_bits,
                                     count=nw_group.amount))
        logger.debug("Base CIDR sliced on subnets: %s", subnets)

        for net in nw_group.networks:
            logger.debug("Deleting old network with id=%s, cidr=%s",
                         net.id, net.cidr)
            ips = db().query(IPAddr).filter(
                IPAddr.network == net.id
            ).all()
            map(db().delete, ips)
            db().delete(net)
            db().commit()
        # Dmitry's hack for clearing VLANs without networks
        self.clear_vlans()
        db().commit()
        nw_group.networks = []

        for n in xrange(nw_group.amount):
            vlan_id = None
            if nw_group.vlan_start is not None:
                vlan_db = db().query(Vlan).get(nw_group.vlan_start + n)
                if vlan_db:
                    logger.warning("Intersection with existing vlan_id: %s",
                                   vlan_db.id)
                else:
                    vlan_db = Vlan(id=nw_group.vlan_start + n)
                    db().add(vlan_db)
                vlan_id = vlan_db.id
                logger.debug("Created VLAN object, vlan_id=%s", vlan_id)
            gateway = None
            if nw_group.gateway:
                gateway = nw_group.gateway
            net_db = Network(
                release=nw_group.release,
                name=nw_group.name,
                access=nw_group.access,
                cidr=str(subnets[n]),
                vlan_id=vlan_id,
                gateway=gateway,
                network_group_id=nw_group.id)
            db().add(net_db)
        db().commit()
开发者ID:mahak,项目名称:fuelweb,代码行数:56,代码来源:manager.py

示例10: discovery_rule

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def discovery_rule(ip_range,proxy_hostid,proxy_name):
	"""
	criar/atualizar a regra dentro do zabbix, passando apenas o range de ip
	ignora o primeiro ip e os 2 ultimos
	aceita de /19 ate /32
	"""
	rule_name = 'SNMP_auto - {0}'.format(ip_range)
	ip = IPNetwork(ip_range)
	ip_list = list(ip)
	ip_range_small = ''
	if ip.prefixlen >= 30:
		ip_range_small = ip_range
	elif ip.prefixlen >= 24 and ip.prefixlen < 30:
		ip_range_small = '{0}-{1}'.format(str(ip_list[2]), str(ip_list[-4]).split('.')[3])
	elif ip.prefixlen > 18 and ip.prefixlen < 24:
		nets = list(ip.subnet(24))
		for index in range(nets.__len__()):
			ip_list = list(IPNetwork(nets[index]))
			if index == 0: # Primeiro
				ip_range_small = '{0}-{1}'.format(str(ip_list[2]), str(ip_list[-1]).split('.')[3])
			elif index == (nets.__len__()-1): # Ultimo
				ip_range_small = '{0},{1}-{2}'.format(ip_range_small,str(ip_list[2]), str(ip_list[-4]).split('.')[3])
			else: # Do meio
				ip_range_small = '{0},{1}-{2}'.format(ip_range_small,str(ip_list[1]), str(ip_list[-1]).split('.')[3])
	else:
		logger.warning('Tamanho de rede invalido: {0}'.format(ip_range))
	dchecks = discovery_checks()
	out={ 'druleids': 'fake data' }
	exists = zapi.drule.get(output=['name'],filter={'name': rule_name})
	params = { 'name': rule_name, 'iprange': ip_range_small, 'delay': '86400', 'proxy_hostid': proxy_hostid, 'dchecks': dchecks, 'status': 1 }
	if exists.__len__() == 1:
		query = {
			'output':[ 'druleids' ],
			'search': { 'name': rule_name }
		}
		params['druleid'] = zapi.drule.get(**query)[0]['druleid']
		if not args.move:
			del params['proxy_hostid']
		if not fake:
			out = zapi.drule.update(**params)
	elif exists.__len__() == 0:
		# Nao existe a regra de discovery ainda..
		if not fake:
			out = zapi.drule.create(**params) #fecha zapi.drule.create
	else:
		logger.error('Too many discovery rules for {0}: {1}'.format(rule_name,exists.__len__()))

	if ( out or fake ):
		logger.debug('\t{0} --> rule {1} ({2})'.format(proxy_name,rule_name,out['druleids']))
	else:
		logger.error('\tFAILED:\t{0} --> rule {1} ({2})'.format(proxy_name,rule_name,out['druleids']))
	return
开发者ID:fehraraujo,项目名称:zabbix-scripts,代码行数:54,代码来源:zbx_discovery-manager.py

示例11: get_pool_dict_list

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def get_pool_dict_list(cidr, max_length=4):
    # Assuming a /24 subnet in cidr
    final_list = []
    cidr_object = IPNetwork(cidr)
    subnets_list = list(cidr_object.subnet(29))
    random.shuffle(subnets_list)
    list_length = random.randint(1, max_length)

    for i in range(0, list_length):
        subnet = subnets_list[i]
        pool_dict = {'start': str(subnet[0]), 'end': str(subnet[-1])}
        final_list.append(pool_dict)
    return final_list
开发者ID:Ankitja,项目名称:contrail-test,代码行数:15,代码来源:neutron_util.py

示例12: scan_cn_ip

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def scan_cn_ip():
    rtree = ipRadixDB()
    all_done = True
    f = open("input/delegated-apnic-latest","r")
    count = 0
    try:
        for line in f.readlines():
            if count % 100 == 0:
                logger.info("==============================>[%s]", str(count))
            count += 1
            #l = line.decode("utf-8")
            params = line.split("|")
            if len(params) >=4 and params[1] == 'CN' and params[2] == "ipv4" and params[3] != "*":
                network = params[3]
                prefixlen = 32 - int(math.log(int(params[4]), 2))
                prefix = network + '/' + str(prefixlen)
                if int(prefixlen) > 24:
                    networks = IPNetwork(network+'/'+'24')
                    subnetworks = networks.subnet(24)
                else:
                    networks = IPNetwork(prefix)
                    subnetworks = networks.subnet(24)
                for sub in subnetworks:
                    network, prefixlen = str(sub).split("/")
                    ip = generate_random_ip(network, int(prefixlen))
                    
                    rtree.addPrefix(network, int(prefixlen))
                    jsonData = query_local(ip)
                    data_key = ["country", "province", "city", "isp"]
                    node  = rtree.rnode
                    for key in data_key:
                        node.data[key] = jsonData.get(key,"")
                    node.data["ip"] = ip
                    logger.info("%s [%s] [%s] [%s]" % (ip, prefix, str(sub), node.data["province"]))

    except Exception, e:
        logger.error(e)
        all_done = False
开发者ID:licheng-xd,项目名称:ipdb_creator,代码行数:40,代码来源:fully_update_cn.py

示例13: check_idc_net

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
def check_idc_net(client, net):
    subnets = net.get('subnets', [])
    if not subnets:
        print('%s has no subnet' % net['id'])
        return ([], [])
    subnet_id = subnets[0]
    subnet = client.show_subnet(subnet_id)['subnet']
    if not subnet:
        print('%s has no subnet' % net['id'])
        return ([], [])
    host_routes = subnet['host_routes']
    link_route = None
    private_ip_routes = []
    public_services_routes = []
    new_routes = []
    need_update = False
    gateway = None
    for route in host_routes:
        nexthop = route['nexthop']
        destination = route['destination']
        if nexthop == '0.0.0.0':
            link_route = route
            gateway = str(IPNetwork(destination).ip + 1)
        elif destination in ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']:
            private_ip_routes.append(route)
        else:
            public_services_routes.append(route)
    if not link_route:
        print('subnet %s has no link scope route' % subnet_id)
        return ([], [])
    new_routes.append(link_route)
    if len(private_ip_routes) != 3:
        print('%s private ips routes are incorrect' % net['id'])
        need_update = True
    new_routes.extend([
        {'destination': '10.0.0.0/8', 'nexthop': gateway, 'order': 10},
        {'destination': '172.16.0.0/12', 'nexthop': gateway, 'order': 10},
        {'destination': '192.168.0.0/16', 'nexthop': gateway, 'order': 10}
    ])
    pub_cidrs = []
    for cidr in public_service_cidrs.split(','):
        pn = IPNetwork(cidr)
        pub_cidrs.extend([str(c) for c in pn.subnet(pn.prefixlen + 1)])
    new_pub_routes = [{'destination': c, 'nexthop': gateway, 'order': 10}
                      for c in pub_cidrs]
    if (set([r['destination'] for r in new_pub_routes])
            != set([r['destination'] for r in public_services_routes])):
        need_update = True
    new_routes.extend(new_pub_routes)
    return (new_routes, host_routes) if need_update else ([], host_routes)
开发者ID:superekcah,项目名称:utils,代码行数:52,代码来源:update_routes.py

示例14: _allocateIrb

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
    def _allocateIrb(self, session, pod, irbPrefix, leafs):
        irbIp = IPNetwork(irbPrefix).network
        numOfHostIpsPerSwitch = pod.hostOrVmCountPerLeaf
        numOfSubnets = len(leafs)
        bitsPerSubnet = int(math.ceil(math.log(numOfHostIpsPerSwitch + 2, 2)))  # +2 for network and broadcast
        cidrForEachSubnet = 32 - bitsPerSubnet

        numOfIps = (numOfSubnets * (2 ** bitsPerSubnet))
        numOfBits = int(math.ceil(math.log(numOfIps, 2))) 
        cidr = 32 - numOfBits
        irbBlock = IPNetwork(str(irbIp) + "/" + str(cidr))
        irbSubnets = list(irbBlock.subnet(cidrForEachSubnet))
        
        pod.allocatedIrbBlock = str(irbBlock.cidr)
        self._assignAllocatedIrbToDevices(session, leafs, irbSubnets, cidrForEachSubnet)
开发者ID:Juniper,项目名称:OpenClos,代码行数:17,代码来源:l3Clos.py

示例15: _init_vpn

# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import subnet [as 别名]
    def _init_vpn(self):
        self.create_user()
        cpsdirector.common.config_parser.set('conpaas', 'VPN_BASE_NETWORK', 
                                             '172.16.0.0')
        cpsdirector.common.config_parser.set('conpaas', 'VPN_NETMASK', 
                                             '255.240.0.0')
        cpsdirector.common.config_parser.set('conpaas', 'VPN_SERVICE_BITS', 
                                             '6')

        from netaddr import IPNetwork
        base_net = IPNetwork('172.16.0.0/255.240.0.0')
        for subnet in base_net.subnet(24):
            vpn = str(subnet)
            break
        return vpn
开发者ID:ConPaaS-team,项目名称:conpaas,代码行数:17,代码来源:test.py


注:本文中的netaddr.IPNetwork.subnet方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。