本文整理汇总了Python中ipcalc.Network类的典型用法代码示例。如果您正苦于以下问题:Python Network类的具体用法?Python Network怎么用?Python Network使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Network类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clean
def clean(self):
super(Prefix4, self).clean()
prefix = self.prefix
if re.match(r'(\d{1,3}\.){3}\d{1,3}[\s]*$', prefix):
self.prefix = prefix + '/32'
elif re.match(r'(\d{1,3}\.){3}\d{1,3}/\d{1,2}', prefix):
pass
else:
raise ValidationError(u'Invalid network prefix "{0}"'.format(prefix))
network = Network(str(self.prefix))
if network.network().dq != network.dq:
raise ValidationError(u'Invalid prefix length /{0}'
u' for the network {1}'.format(self.prefix.split('/')[1], self.prefix.split('/')[0]))
# qs = self.vrf_list(exclude_self=True)
if not self.find_parent() and not self.domain:
ValidationError(u'Top-level prefix must have domain name')
if self.status in BLOCK_STATUSES:
p = self.prefixes_lower(statuses=BLOCK_STATUSES).first()
if not p:
p = self.prefixes_upper(statuses=BLOCK_STATUSES).last()
if p:
raise ValidationError(u'Network {0} is already {1}'.format(p.prefix, p.get_status_display().lower()))
示例2: prefixes_lower
def prefixes_lower(self, root_only=False, networks_only=False, hosts_only=False, statuses=None,
ignore_stored_values=False):
if self.id and root_only and not ignore_stored_values:
args = {}
if networks_only:
args['size__gt'] = 1
elif hosts_only:
args['size'] = 1
if statuses:
args['status__in'] = statuses
return self.child if len(args) == 0 else self.child.filter(**args)
network = Network(str(self.prefix))
f_ip = network.ip
l_ip = network.broadcast_long()
qs = self.vrf.prefixes(
networks_only=networks_only,
hosts_only=hosts_only,
statuses=statuses).filter(first_ip_dec__gte=f_ip, last_ip_dec__lte=l_ip)
if ignore_stored_values:
# TODO Add check with ignoring stored data
pass
else:
if self.id:
qs = qs.exclude(id=self.id)
if root_only:
return qs.filter(parent=self.find_parent())
else:
return qs
示例3: search_free
def search_free(vrf, network, statuses):
"""
Free blocks recursive search
:param vrf: VRF
:type vrf: Vrf
:param network: Network
:type network: Network
"""
f_ip = network.ip
l_ip = network.broadcast_long()
size = network.size()
blocked_size = \
vrf.prefixes().filter(status__in=statuses, first_ip_dec__gte=f_ip, last_ip_dec__lte=l_ip).aggregate(
sum_size=Sum('size'))['sum_size']
if not blocked_size:
blocked_size = 0
if size == blocked_size:
return []
elif blocked_size == 0:
if vrf.prefixes().filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip):
parent = vrf.prefixes().filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip).last()
else:
parent = None
if size == 1:
create_url = '{0}?prefix={1}'.format(reverse_lazy('ipam.host4_add', kwargs={'vrf': vrf.name}),
network.dq)
else:
create_url = '{0}?prefix={1}'.format(reverse_lazy('ipam.prefix4_add', kwargs={'vrf': vrf.name}),
network)
return [{'prefix': str(network), 'parent': parent, 'create_url': create_url}]
else:
net_1 = Network('{0}/{1}'.format(network.to_tuple()[0], network.to_tuple()[1] + 1))
net_2 = Network('{0}/{1}'.format(IP(net_1.broadcast_long() + 1).dq, network.subnet() + 1))
return search_free(vrf, net_1, statuses) + search_free(vrf, net_2, statuses)
示例4: prefixes_upper
def prefixes_upper(self, networks_only=False, hosts_only=False, statuses=None):
network = Network(str(self.prefix))
f_ip = network.ip
l_ip = network.broadcast_long()
if self.id:
return self.vrf.prefixes(networks_only=networks_only, hosts_only=hosts_only, statuses=statuses).filter(
first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip, size__gt=network.size()).exclude(id=self.id)
else:
return self.vrf.prefixes(networks_only=networks_only, hosts_only=hosts_only, statuses=statuses).filter(
first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip, size__gt=network.size())
示例5: test_calculation
def test_calculation(self):
self.assertEqual(self.network[1].subnet(), 24)
a = Network('192.168.0.100/28')
self.assertEqual(str(a), '192.168.0.100/28')
self.assertEqual(a.size(), 16)
self.assertEqual(a.size(), len(a))
self.assertEqual(int(a), 0xC0A80064)
for i in range(a.size()):
self.assertEqual(int(a[i]), i + 0xC0A80064)
self.assertRaises(IndexError, lambda: a[a.size()])
示例6: search
def search(user, search_args):
"""
:param user: User
:type user: django.contrib.auth.models.User
:param search_args: String list
:type search_args: list
:return: List of results: {title, utl, description, module}
"""
if not user.has_perms(['ipam.view', ]):
return []
else:
ip = None
string_args = []
ip_reg_exp = re.compile('(\d{1,3}\.)\d{1,3}(/\d{1,3})?')
for line in search_args:
if ip_reg_exp.match(line) and not ip:
ip = line if '/' in line else line + '/32'
else:
string_args.append(line)
objects = []
# Search Prefix4
qs = Prefix4.objects.all()
if ip:
network = Network(ip)
f_ip = network.ip
l_ip = network.broadcast_long()
qs = qs.filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip)
for s in string_args:
qs = qs.filter(Q(description__icontains=s) | Q(status__icontains=s) | Q(domain__icontains=s) | Q(
host_name__icontains=s))
if qs:
objects.append(qs.last())
qs = Prefix4.objects.all()
for s in search_args:
qs = qs.filter(Q(description__icontains=s) | Q(status__icontains=s) | Q(domain__icontains=s) | Q(
host_name__icontains=s) | Q(prefix__icontains=s))
for prefix in qs:
if prefix not in objects:
objects.append(prefix)
qs = Vrf.objects.all()
for s in search_args:
qs = qs.filter(Q(description__icontains=s) | Q(rd__icontains=s) | Q(name__icontains=s))
for vrf in qs:
if vrf not in objects:
objects.append(vrf)
return [{'title': str(o), 'url': o.get_absolute_url(), 'description': o.description, 'module': 'IPAM'} for o in
objects]
示例7: TestNetwork
class TestNetwork(unittest.TestCase):
"""Tests for Network."""
def setUp(self):
self.network = Network('192.168.11.0/255.255.255.0')
def test_calculation(self):
self.assertEqual(self.network[1].subnet(), 24)
a = Network('192.168.0.100/28')
self.assertEqual(str(a), '192.168.0.100/28')
self.assertEqual(a.size(), 16)
self.assertEqual(a.size(), len(a))
self.assertEqual(int(a), 0xC0A80064)
for i in range(a.size()):
self.assertEqual(int(a[i]), i + 0xC0A80064)
self.assertRaises(IndexError, lambda: a[a.size()])
def test_indexers(self):
expected = range(int(0xC0A80B00), int(0xC0A80C00))
self.assertEqual(self.network.size(), len(expected))
for i in range(self.network.size()):
self.assertEqual(int(self.network[i]), expected[i])
self.assertEqual(int(self.network[-1]), expected[-1])
def test_contains(self):
self.assertTrue(IP('192.168.11.0') in self.network)
self.assertTrue(IP('192.168.11.1') in self.network)
self.assertTrue(IP('192.168.11.255') in self.network)
def test_eq_le_gt(self):
self.assertEqual(Network('192.168.11.0'), Network('192.168.11.0'))
self.assertEqual(Network('192.168.11.0/32'), Network('192.168.11.0'))
self.assertEqual(Network('192.168.11.0'), IP('192.168.11.0'))
self.assertEqual(Network('192.168.11.0/32'), IP('192.168.11.0'))
self.assertNotEqual(Network('192.168.11.0/28'), Network('192.168.11.0/24'))
self.assertNotEqual(Network('192.168.11.0'), Network('192.168.11.1'))
self.assertNotEqual(Network('192.168.11.0'), Network('192.168.2.1'))
self.assertNotEqual(Network('192.168.11.0/30'), IP('192.168.11.0'))
self.assertNotEqual(Network('192.168.1.0'), IP('192.168.11.0'))
self.assertTrue(Network('192.168.1.0/30') < Network('192.168.1.0/29'))
self.assertTrue(Network('192.168.1.0/30') <= Network('192.168.1.0/29'))
self.assertTrue(Network('192.168.1.0/30') <= Network('192.168.1.0/30'))
self.assertTrue(Network('192.168.1.0/28') > Network('192.168.1.0/29'))
self.assertTrue(Network('192.168.1.0/28') >= Network('192.168.1.0/29'))
self.assertTrue(Network('192.168.1.0/28') >= Network('192.168.1.0/28'))
示例8: get_context_data
def get_context_data(self, **kwargs):
from django.db.models import Sum
from ipam.models import BLOCK_STATUSES
def search_free(vrf, network, statuses):
"""
Free blocks recursive search
:param vrf: VRF
:type vrf: Vrf
:param network: Network
:type network: Network
"""
f_ip = network.ip
l_ip = network.broadcast_long()
size = network.size()
blocked_size = \
vrf.prefixes().filter(status__in=statuses, first_ip_dec__gte=f_ip, last_ip_dec__lte=l_ip).aggregate(
sum_size=Sum('size'))['sum_size']
if not blocked_size:
blocked_size = 0
if size == blocked_size:
return []
elif blocked_size == 0:
if vrf.prefixes().filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip):
parent = vrf.prefixes().filter(first_ip_dec__lte=f_ip, last_ip_dec__gte=l_ip).last()
else:
parent = None
if size == 1:
create_url = '{0}?prefix={1}'.format(reverse_lazy('ipam.host4_add', kwargs={'vrf': vrf.name}),
network.dq)
else:
create_url = '{0}?prefix={1}'.format(reverse_lazy('ipam.prefix4_add', kwargs={'vrf': vrf.name}),
network)
return [{'prefix': str(network), 'parent': parent, 'create_url': create_url}]
else:
net_1 = Network('{0}/{1}'.format(network.to_tuple()[0], network.to_tuple()[1] + 1))
net_2 = Network('{0}/{1}'.format(IP(net_1.broadcast_long() + 1).dq, network.subnet() + 1))
return search_free(vrf, net_1, statuses) + search_free(vrf, net_2, statuses)
context = super(FreeBlocks4ReportView, self).get_context_data(**kwargs)
context['page_title'] = u'Free IPv4 Blocks'
if 'vrf' in self.request.GET and 'prefix' in self.request.GET:
if Vrf.objects.filter(name=self.request.GET['vrf']):
net = Network(self.request.GET['prefix'])
if net.dq != net.network():
net = Network('{0}/{1}'.format(net.network(), net.subnet()))
context['report'] = search_free(Vrf.objects.get(name=self.request.GET['vrf']), net, BLOCK_STATUSES)
context['total'] = len(context['report'])
return context
示例9: new_isp_ip
def new_isp_ip():
with open('new_isp_ip.txt', 'w') as f:
for line in open('isp_ip.txt'):
line = line.strip()
if line:
elems = [e.strip() for e in line.split('/')]
try:
mask = int(elems[1])
except ValueError:
f.write(','.join(elems) + '\n')
continue
network = Network(elems[0], mask=mask)
elems[0] = network.network().dq
elems[1] = network.broadcast().dq
f.write(','.join(elems) + '\n')
示例10: test_ipv4_3
def test_ipv4_3(self):
net = Network('10.10.0.0/255.255.255.0')
self.assertTrue(str(net) == '10.10.0.0/24')
self.assertTrue(str(net.to_ipv6().to_compressed()) == '2002:a0a::')
self.assertTrue(net.info() == 'PRIVATE')
self.assertTrue(net.subnet() == 24)
self.assertTrue(net.size() == 1 << (32 - 24))
self.assertTrue(int(net) == 0x0a0a0000)
self.assertTrue(net.hex().lower() == '0a0a0000')
self.assertTrue(str(net.netmask()) == '255.255.255.0')
self.assertTrue(net.version() == 4)
self.assertTrue(str(net.network()) == '10.10.0.0')
self.assertTrue(str(net.broadcast()) == '10.10.0.255')
self.assertFalse('192.168.0.1' in net)
self.assertFalse('192.168.114.128' in net)
self.assertFalse('10.0.0.1' in net)
self.assertTrue('10.10.0.254' in net)
self.assertTrue('10.10.0.100' in net)
示例11: test_ipv4_3
def test_ipv4_3(self):
net = Network("10.10.0.0/255.255.255.0")
self.assertTrue(str(net) == "10.10.0.0/24")
self.assertTrue(str(net.to_ipv6().to_compressed()) == "2002:a0a::")
self.assertTrue(net.info() == "PRIVATE")
self.assertTrue(net.subnet() == 24)
self.assertTrue(net.size() == 1 << (32 - 24))
self.assertTrue(int(net) == 0x0A0A0000)
self.assertTrue(net.hex().lower() == "0a0a0000")
self.assertTrue(str(net.netmask()) == "255.255.255.0")
self.assertTrue(net.version() == 4)
self.assertTrue(str(net.network()) == "10.10.0.0")
self.assertTrue(str(net.broadcast()) == "10.10.0.255")
self.assertFalse("192.168.0.1" in net)
self.assertFalse("192.168.114.128" in net)
self.assertFalse("10.0.0.1" in net)
self.assertTrue("10.10.0.254" in net)
self.assertTrue("10.10.0.100" in net)
示例12: test_ipv4_1
def test_ipv4_1(self):
net = Network("192.168.114.42", 23)
self.assertTrue(str(net) == "192.168.114.42/23")
self.assertTrue(str(net.to_ipv6().to_compressed()) == "2002:c0a8:722a::")
self.assertTrue(net.info() == "PRIVATE")
self.assertTrue(net.subnet() == 23)
self.assertTrue(net.size() == 1 << (32 - 23))
self.assertTrue(int(net) == 0xC0A8722A)
self.assertTrue(net.hex().lower() == "c0a8722a")
self.assertTrue(str(net.netmask()) == "255.255.254.0")
self.assertTrue(net.version() == 4)
self.assertTrue(str(net.network()) == "192.168.114.0")
self.assertTrue(str(net.broadcast()) == "192.168.115.255")
self.assertFalse("192.168.0.1" in net)
self.assertTrue("192.168.114.128" in net)
self.assertFalse("10.0.0.1" in net)
self.assertTrue(str(net + 6) == "192.168.114.48/23")
self.assertTrue((net + 6) in net)
self.assertTrue(str(net - 6) == "192.168.114.36/23")
self.assertTrue((net - 6) in net)
示例13: test_ipv4_1
def test_ipv4_1(self):
net = Network('192.168.114.42', 23)
self.assertTrue(str(net) == '192.168.114.42/23')
self.assertTrue(str(net.to_ipv6().to_compressed()) == '2002:c0a8:722a::')
self.assertTrue(net.info() == 'PRIVATE')
self.assertTrue(net.subnet() == 23)
self.assertTrue(net.size() == 1 << (32 - 23))
self.assertTrue(int(net) == 0xc0a8722a)
self.assertTrue(net.hex().lower() == 'c0a8722a')
self.assertTrue(str(net.netmask()) == '255.255.254.0')
self.assertTrue(net.version() == 4)
self.assertTrue(str(net.network()) == '192.168.114.0')
self.assertTrue(str(net.broadcast()) == '192.168.115.255')
self.assertFalse('192.168.0.1' in net)
self.assertTrue('192.168.114.128' in net)
self.assertFalse('10.0.0.1' in net)
self.assertTrue(str(net + 6) == '192.168.114.48/23')
self.assertTrue((net + 6) in net)
self.assertTrue(str(net - 6) == '192.168.114.36/23')
self.assertTrue((net - 6) in net)
示例14: add_network_cidr_mapping
def add_network_cidr_mapping(self,
network_config):
"""
Method calculates and adds a CloudFormation mapping that is used to set VPC and Subnet CIDR blocks. Calculated based on CIDR block sizes and additionally checks to ensure all network segments fit inside of the specified overall VPC CIDR
@param network_config [dict] dictionary of values containing data for creating
"""
az_count = int(network_config.get('az_count', '2'))
network_cidr_base = str(network_config.get('network_cidr_base', '172.16.0.0'))
network_cidr_size = str(network_config.get('network_cidr_size', '20'))
first_network_address_block = str(network_config.get('first_network_address_block', network_cidr_base))
ret_val = {}
cidr_info = Network(network_cidr_base + '/' + network_cidr_size)
base_cidr = cidr_info.network().to_tuple()[0] + '/' + str(cidr_info.to_tuple()[1])
ret_val['vpcBase'] = {'cidr': base_cidr}
current_base_address = first_network_address_block
subnet_types = network_config.get('subnet_types', ['public', 'private'])
for index in range(0, len(subnet_types)):
subnet_type = subnet_types[index]
subnet_size = network_config.get(subnet_type + '_subnet_size', '22')
if index != 0:
range_reset = Network(current_base_address + '/' + str(subnet_size))
current_base_address = IP(int(range_reset.host_last().hex(), 16) + 2).to_tuple()[0]
for subnet_id in range(0, az_count):
if not cidr_info.check_collision(current_base_address):
raise RuntimeError('Cannot continue creating network--current base address is outside the range of the master Cidr block. Found on pass ' + str(index + 1) + ' when creating ' + subnet_type + ' subnet cidrs')
ip_info = Network(current_base_address + '/' + str(subnet_size))
range_info = ip_info.network().to_tuple()
if 'subnet' + str(subnet_id) not in ret_val:
ret_val['subnet' + str(subnet_id)] = dict()
ret_val['subnet' + str(subnet_id)][subnet_type] = ip_info.network().to_tuple()[0] + '/' + str(ip_info.to_tuple()[1])
current_base_address = IP(int(ip_info.host_last().hex(), 16) + 2).to_tuple()[0]
return self.template.add_mapping('networkAddresses', ret_val)
示例15: prefixes
def prefixes(self, root_only=False, networks_only=False, hosts_only=False, statuses=None, subnet=None,
recursion=False):
"""
Return QuerySet with VRF's prefixes
:param root_only: return top-level's prefixes only
:type root_only: bool
:param networks_only: return networks only (without hosts)
:type networks_only: bool
:param hosts_only: return hosts only (without networks)
:type hosts_only: bool
:param statuses: statuses list for filter
:type statuses: list
:param recursion: Include children VRFs
:type recursion: bool
:return: QuerySet
:rtype: django.db.models.QuerySet
"""
args = {}
if statuses:
args['status__in'] = statuses
if root_only:
args['parent'] = None
if networks_only:
args['size__gt'] = 1
elif hosts_only:
args['size'] = 1
if subnet:
network = Network(subnet)
args['first_ip_dec__gte'] = network.ip
args['last_ip_dec__lte'] = network.broadcast_long()
if recursion:
args['vrf__in'] = self.recursive_children()
return Prefix4.objects.filter(**args)
else:
return self.prefixes_list if len(args) == 0 else self.prefixes_list.filter(**args)