本文整理汇总了Python中ipaddr.IPNetwork类的典型用法代码示例。如果您正苦于以下问题:Python IPNetwork类的具体用法?Python IPNetwork怎么用?Python IPNetwork使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IPNetwork类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: configure_second_admin_cobbler
def configure_second_admin_cobbler(self):
dhcp_template = '/etc/cobbler/dnsmasq.template'
remote = self.d_env.get_admin_remote()
admin_net2 = self.d_env.admin_net2
second_admin_if = settings.INTERFACES.get(admin_net2)
second_admin_ip = str(
self.d_env.nodes().admin.get_ip_address_by_network_name(admin_net2))
admin_net2_object = self.d_env.get_network(name=admin_net2)
second_admin_network = admin_net2_object.ip.ip
second_admin_netmask = admin_net2_object.ip.netmask
network = IPNetwork('{0}/{1}'.format(second_admin_network,
second_admin_netmask))
discovery_subnet = [net for net in network.iter_subnets(1)][-1]
first_discovery_address = str(discovery_subnet.network)
last_discovery_address = str(discovery_subnet.broadcast - 1)
new_range = ('interface={4}\\n'
'dhcp-range=internal2,{0},{1},{2}\\n'
'dhcp-option=net:internal2,option:router,{3}\\n'
'pxe-service=net:internal2,x86PC,"Install",pxelinux,{3}\\n'
'dhcp-boot=net:internal2,pxelinux.0,boothost,{3}\\n').\
format(first_discovery_address, last_discovery_address,
second_admin_netmask, second_admin_ip, second_admin_if)
cmd = ("dockerctl shell cobbler sed -r '$a \{0}' -i {1};"
"dockerctl shell cobbler cobbler sync").format(new_range,
dhcp_template)
result = remote.execute(cmd)
assert_equal(result['exit_code'], 0, ('Failed to add second admin'
'network to cobbler: {0}').format(result))
示例2: clean_int_v4netmaskbit
def clean_int_v4netmaskbit(self):
ip = self.cleaned_data.get("int_ipv4address")
nw = self.cleaned_data.get("int_v4netmaskbit")
if not nw or not ip:
return nw
network = IPNetwork('%s/%s' % (ip, nw))
used_networks = []
qs = models.Interfaces.objects.all()
if self.instance.id:
qs = qs.exclude(id=self.instance.id)
for iface in qs:
if iface.int_v4netmaskbit:
used_networks.append(
IPNetwork('%s/%s' % (
iface.int_ipv4address,
iface.int_v4netmaskbit,
))
)
for alias in iface.alias_set.all():
if alias.alias_v4netmaskbit:
used_networks.append(
IPNetwork('%s/%s' % (
alias.alias_v4address,
alias.alias_v4netmaskbit,
))
)
for unet in used_networks:
if unet.overlaps(network):
raise forms.ValidationError(
_("The network %s is already in use by another NIC.") % (
network.masked(),
)
)
return nw
示例3: clean
def clean(self):
cdata = self.cleaned_data
ipv4key = 'int_ipv4address'
ipv4addr = cdata.get(ipv4key)
ipv4addr_b = cdata.get('int_ipv4address_b')
ipv4net = cdata.get("int_v4netmaskbit")
if ipv4addr and ipv4addr_b and ipv4net:
network = IPNetwork('%s/%s' % (ipv4addr, ipv4net))
if not network.overlaps(
IPNetwork('%s/%s' % (ipv4addr_b, ipv4net))
):
self._errors['int_ipv4address_b'] = self.error_class([
_('The IP must be within the same network')
])
ipv6addr = cdata.get("int_ipv6address")
ipv6net = cdata.get("int_v6netmaskbit")
ipv4 = True if ipv4addr and ipv4net else False
ipv6 = True if ipv6addr and ipv6net else False
# IF one field of ipv4 is entered, require the another
if (ipv4addr or ipv4net) and not ipv4:
if not (ipv4addr or ipv4addr_b) and not self._errors.get(ipv4key):
self._errors[ipv4key] = self.error_class([
_("You have to specify IPv4 address as well"),
])
if not ipv4net and 'int_v4netmaskbit' not in self._errors:
self._errors['int_v4netmaskbit'] = self.error_class([
_("You have to choose IPv4 netmask as well"),
])
# IF one field of ipv6 is entered, require the another
if (ipv6addr or ipv6net) and not ipv6:
if not ipv6addr and not self._errors.get('int_ipv6address'):
self._errors['int_ipv6address'] = self.error_class([
_("You have to specify IPv6 address as well"),
])
if not ipv6net:
self._errors['int_v6netmaskbit'] = self.error_class([
_("You have to choose IPv6 netmask as well"),
])
if ipv6 and ipv4:
self._errors['__all__'] = self.error_class([
_("You have to choose between IPv4 or IPv6"),
])
vip = cdata.get("int_vip")
if vip and not ipv4addr_b:
self._errors['int_ipv4address_b'] = self.error_class([
_("This field is required for failover")
])
if vip and not ipv4addr:
self._errors['int_ipv4address'] = self.error_class([
_("This field is required for failover")
])
return cdata
示例4: clean_alias_v4netmaskbit
def clean_alias_v4netmaskbit(self):
vip = self.cleaned_data.get("alias_vip")
ip = self.cleaned_data.get("alias_v4address")
nw = self.cleaned_data.get("alias_v4netmaskbit")
if not nw or not ip:
return nw
network = IPNetwork("%s/%s" % (ip, nw))
if vip:
if not network.overlaps(IPNetwork("%s/%s" % (vip, nw))):
raise forms.ValidationError(_("Virtual IP is not in the same network"))
if self.instance.id and self.instance.alias_interface.int_interface.startswith("carp"):
return nw
used_networks = []
qs = models.Interfaces.objects.all().exclude(int_interface__startswith="carp")
if self.instance.id:
qs = qs.exclude(id=self.instance.alias_interface.id)
elif self.parent.instance.id:
qs = qs.exclude(id=self.parent.instance.id)
for iface in qs:
if iface.int_v4netmaskbit:
used_networks.append(IPNetwork("%s/%s" % (iface.int_ipv4address, iface.int_v4netmaskbit)))
for alias in iface.alias_set.all():
if alias.alias_v4netmaskbit:
used_networks.append(IPNetwork("%s/%s" % (alias.alias_v4address, alias.alias_v4netmaskbit)))
for unet in used_networks:
if unet.overlaps(network):
raise forms.ValidationError(_("The network %s is already in use by another NIC.") % (network.masked(),))
return nw
示例5: configure_second_admin_cobbler
def configure_second_admin_cobbler(self):
dhcp_template = '/etc/cobbler/dnsmasq.template'
remote = self.get_admin_remote()
main_admin_ip = str(self.nodes().admin.
get_ip_address_by_network_name(self.admin_net))
second_admin_ip = str(self.nodes().admin.
get_ip_address_by_network_name(self.admin_net2))
second_admin_network = self.get_network(self.admin_net2).split('/')[0]
second_admin_netmask = self.get_net_mask(self.admin_net2)
network = IPNetwork('{0}/{1}'.format(second_admin_network,
second_admin_netmask))
discovery_subnet = [net for net in network.iter_subnets(1)][-1]
first_discovery_address = str(discovery_subnet.network)
last_discovery_address = str(discovery_subnet.broadcast - 1)
new_range = ('dhcp-range=internal2,{0},{1},{2}\\n'
'dhcp-option=net:internal2,option:router,{3}\\n'
'dhcp-boot=net:internal2,pxelinux.0,boothost,{4}\\n').\
format(first_discovery_address, last_discovery_address,
second_admin_netmask, second_admin_ip, main_admin_ip)
cmd = ("dockerctl shell cobbler sed -r '$a \{0}' -i {1};"
"dockerctl shell cobbler cobbler sync").format(new_range,
dhcp_template)
result = remote.execute(cmd)
assert_equal(result['exit_code'], 0, ('Failed to add second admin'
'network to cobbler: {0}').format(result))
示例6: clean
def clean(self):
cdata = self.cleaned_data
ipv4vip = cdata.get("alias_vip")
ipv4addr = cdata.get("alias_v4address")
ipv4net = cdata.get("alias_v4netmaskbit")
ipv6addr = cdata.get("alias_v6address")
ipv6net = cdata.get("alias_v6netmaskbit")
ipv4 = True if ipv4addr and ipv4net else False
ipv6 = True if ipv6addr and ipv6net else False
# IF one field of ipv4 is entered, require the another
if (ipv4addr or ipv4net) and not ipv4:
if not ipv4addr and not self._errors.get('alias_v4address'):
self._errors['alias_v4address'] = self.error_class([
_("You have to specify IPv4 address as well per alias"),
])
if not ipv4net and 'alias_v4netmaskbit' not in self._errors:
self._errors['alias_v4netmaskbit'] = self.error_class([
_("You have to choose IPv4 netmask as well per alias"),
])
# IF one field of ipv6 is entered, require the another
if (ipv6addr or ipv6net) and not ipv6:
if not ipv6addr and not self._errors.get('alias_v6address'):
self._errors['alias_v6address'] = self.error_class([
_("You have to specify IPv6 address as well per alias"),
])
if not ipv6net:
self._errors['alias_v6netmaskbit'] = self.error_class([
_("You have to choose IPv6 netmask as well per alias"),
])
if ipv6 and ipv4:
self._errors['__all__'] = self.error_class([
_("You have to choose between IPv4 or IPv6 per alias"),
])
configured_vip = False
if ipv4vip and hasattr(self, 'parent'):
iface = self.parent.instance
ip = IPNetwork('%s/32' % ipv4vip)
network = IPNetwork('%s/%s' % (
iface.int_ipv4address,
iface.int_v4netmaskbit,
))
if ip.overlaps(network):
configured_vip = True
if (
not configured_vip and not ipv6 and not (ipv6addr or ipv6net) and
not ipv4 and not (ipv4addr or ipv4net)
):
self._errors['__all__'] = self.error_class([
_("You must specify either an valid IPv4 or IPv6 with maskbit "
"per alias"),
])
return cdata
示例7: clean
def clean(self):
cdata = self.cleaned_data
_n = notifier()
if not _n.is_freenas() and _n.failover_licensed():
from freenasUI.failover.models import Failover
try:
if Failover.objects.all()[0].disabled is False:
self._errors["__all__"] = self.error_class(
[_("Failover needs to be disabled to perform network " "changes.")]
)
except:
log.warn("Failed to verify failover status", exc_info=True)
ipv4key = "int_ipv4address"
ipv4addr = cdata.get(ipv4key)
ipv4addr_b = cdata.get("int_ipv4address_b")
ipv4net = cdata.get("int_v4netmaskbit")
if ipv4addr and ipv4addr_b and ipv4net:
network = IPNetwork("%s/%s" % (ipv4addr, ipv4net))
if not network.overlaps(IPNetwork("%s/%s" % (ipv4addr_b, ipv4net))):
self._errors["int_ipv4address_b"] = self.error_class([_("The IP must be within the same network")])
ipv6addr = cdata.get("int_ipv6address")
ipv6net = cdata.get("int_v6netmaskbit")
ipv4 = True if ipv4addr and ipv4net else False
ipv6 = True if ipv6addr and ipv6net else False
# IF one field of ipv4 is entered, require the another
if (ipv4addr or ipv4net) and not ipv4:
if not (ipv4addr or ipv4addr_b) and not self._errors.get(ipv4key):
self._errors[ipv4key] = self.error_class([_("You have to specify IPv4 address as well")])
if not ipv4net and "int_v4netmaskbit" not in self._errors:
self._errors["int_v4netmaskbit"] = self.error_class([_("You have to choose IPv4 netmask as well")])
# IF one field of ipv6 is entered, require the another
if (ipv6addr or ipv6net) and not ipv6:
if not ipv6addr and not self._errors.get("int_ipv6address"):
self._errors["int_ipv6address"] = self.error_class([_("You have to specify IPv6 address as well")])
if not ipv6net:
self._errors["int_v6netmaskbit"] = self.error_class([_("You have to choose IPv6 netmask as well")])
if ipv6 and ipv4:
self._errors["__all__"] = self.error_class([_("You have to choose between IPv4 or IPv6")])
vip = cdata.get("int_vip")
dhcp = cdata.get("int_dhcp")
if not dhcp:
if vip and not ipv4addr_b:
self._errors["int_ipv4address_b"] = self.error_class([_("This field is required for failover")])
if vip and not ipv4addr:
self._errors["int_ipv4address"] = self.error_class([_("This field is required for failover")])
return cdata
示例8: generate_networks_for_template
def generate_networks_for_template(self, template, ip_nets,
ip_prefixlen):
"""Slice network to subnets for template.
Generate networks from network template and ip_nets descriptions
for node groups and value to slice that descriptions. ip_nets is a
dict with key named as nodegroup and strings values for with
description of network for that nodegroup in format '127.0.0.1/24'
to be sliced in pieces for networks. ip_prefixlen - the amount the
network prefix length should be sliced by. 24 will create networks
'127.0.0.1/24' from network '127.0.0.1/16'.
:param template: Yaml template with network assignments on interfaces.
:param ip_nets: Dict with network descriptions.
:param ip_prefixlen: Integer for slicing network prefix.
:return: Data to be used to assign networks to nodes.
"""
networks_data = []
nodegroups = self.fuel_web.client.get_nodegroups()
for nodegroup, section in template['adv_net_template'].items():
networks = [(n, section['network_assignments'][n]['ep'])
for n in section['network_assignments']]
assert_true(any(n['name'] == nodegroup for n in nodegroups),
'Network templates contains settings for Node Group '
'"{0}", which does not exist!'.format(nodegroup))
group_id = [n['id'] for n in nodegroups if
n['name'] == nodegroup][0]
ip_network = IPNetwork(ip_nets[nodegroup])
ip_subnets = ip_network.subnet(
int(ip_prefixlen) - int(ip_network.prefixlen))
for network, interface in networks:
ip_subnet = ip_subnets.pop()
networks_data.append(
{
'name': network,
'cidr': str(ip_subnet),
'group_id': group_id,
'interface': interface,
'gateway': None,
'meta': {
"notation": "ip_ranges",
"render_type": None,
"map_priority": 0,
"configurable": True,
"unmovable": False,
"use_gateway": False,
"render_addr_mask": None,
'ip_range': [str(ip_subnet[1]), str(ip_subnet[-2])]
}
}
)
return networks_data
示例9: freeIps
def freeIps(self):
"""Number of free Ips left in this network.
"""
freeips = 0
try:
net = IPNetwork(ipunwrap(self.id))
freeips = int(math.pow(2, net.max_prefixlen - self.netmask) - self.countIpAddresses())
if self.netmask > net.max_prefixlen:
return freeips
return freeips - 2
except ValueError:
for net in self.children():
freeips += net.freeIps()
return freeips
示例10: calcSubnet
def calcSubnet(cidr, positional=1):
net = IPNetwork(args.CIDR)
try:
subnet = list(net.subnet(positional))
except ValueError:
finalcidr = int(cidr.split('/')[1]) + positional
print "[%s] is out of range with [%s] positions away (A /%s, seriously?). Cannot calculate." % (cidr, positional, finalcidr)
raise SystemExit
newcidr = subnet[0].prefixlen
count = len(subnet)
print "[%s] hosts with [/%s] (diff of %s)" % (count, newcidr, positional)
for i in subnet:
print "--%s" % i
示例11: getNetworksFromRoutes
def getNetworksFromRoutes():
from scapy.all import conf, ltoa, read_routes
from ipaddr import IPNetwork, IPAddress
## Hide the 'no routes' warnings
conf.verb = 0
networks = []
for nw, nm, gw, iface, addr in read_routes():
n = IPNetwork( ltoa(nw) )
(n.netmask, n.gateway, n.ipaddr) = [IPAddress(x) for x in [nm, gw, addr]]
n.iface = iface
if not n.compressed in networks:
networks.append(n)
return networks
示例12: handle
def handle(self, *args, **options):
if len(args) == 0:
network, pattern = self.defaultnetwork, self.defaultpattern
if len(args) == 1:
network, pattern = IPNetwork(args[0]), self.defaultpattern
if len(args) == 2:
network, pattern = IPNetwork(args[0]), args[1]
for ip in network.iterhosts():
name = reverse(ip)
content = pattern % dict(
[(str(k), v) for k, v in enumerate(str(ip).split('.'))])
# print "%s\tcreated: %s" % (
# Record.objects.get_or_create(domain=self.get_domain(content),
# name=content, type='A', defaults={'content': str(ip)}))
print "%s\t\tcreated: %s" % (
Record.objects.get_or_create(domain=self.get_domain(name),
name=name, type='PTR', defaults={'content': content}))
示例13: generate_networks_for_template
def generate_networks_for_template(self, template, ip_network,
ip_prefixlen):
networks_data = []
nodegroups = self.fuel_web.client.get_nodegroups()
for nodegroup, section in template['adv_net_template'].items():
networks = [(n, section['network_assignments'][n]['ep'])
for n in section['network_assignments']]
assert_true(any(n['name'] == nodegroup for n in nodegroups),
'Network templates contains settings for Node Group '
'"{0}", which does not exist!'.format(nodegroup))
group_id = [n['id'] for n in nodegroups if
n['name'] == nodegroup][0]
ip_network = IPNetwork(ip_network)
ip_subnets = ip_network.subnet(
int(ip_prefixlen) - int(ip_network.prefixlen))
for network, interface in networks:
ip_subnet = ip_subnets.pop()
networks_data.append(
{
'name': network,
'cidr': str(ip_subnet),
'group_id': group_id,
'interface': interface,
'gateway': None,
'meta': {
"notation": "ip_ranges",
"render_type": None,
"map_priority": 0,
"configurable": True,
"unmovable": False,
"use_gateway": False,
"render_addr_mask": None,
'ip_range': [str(ip_subnet[1]), str(ip_subnet[-2])]
}
}
)
return networks_data
示例14: number
argparser.add_argument('--peer-as', metavar='ASNUM', dest='peer_as', default='65500', help='BGP peer AS number (default: 65500)')
argparser.add_argument('--local-cidr', metavar='CIDR', required=True, dest='local_cidr', help='BGP sessions source addresses block (no default)')
argparser.add_argument('--local-as', metavar='ASNUM', dest='local_as', default='65501', help='BGP local AS number (default: 65501)')
argparser.add_argument('--local-interface', metavar='INTERFACE', dest='local_interface', help='local interface used for BGP sessions source addresses (default: none)')
argparser.add_argument('--announce-cidr', metavar='CIDR', dest='announce_cidr', help='BGP /32 announces block (default: none)')
argparser.add_argument('--sessions', metavar='COUNT', dest='sessions', default=1, help='number of BGP sessions to establish (default: 1)')
args = argparser.parse_args()
# validate command-line options
try:
peer_ip = IPAddress(args.peer_ip)
except:
print 'invalid peer address "%s" - aborting' % args.peer_ip
sys.exit(1)
try:
local_cidr = IPNetwork(args.local_cidr)
except:
print 'invalid local addresses block "%s" - aborting' % args.local_cidr
sys.exit(1)
if args.announce_cidr:
try:
announce_cidr = IPNetwork(args.announce_cidr)
announce_cidr = announce_cidr.iterhosts()
except:
print 'invalid announce addresses block %s - aborting' % args.announce_cidr
sys.exit(1)
# create ExaBGP configuration + setup address aliases if required
configuration = 'group peers {\n'
sessions = 0
for address in local_cidr.iterhosts():
示例15: clean
def clean(self):
cdata = self.cleaned_data
_n = notifier()
if (
not _n.is_freenas() and _n.failover_licensed() and
_n.failover_status() != 'SINGLE' and (
self.instance.id and self.instance.int_vip
)
):
from freenasUI.failover.models import Failover
try:
if Failover.objects.all()[0].disabled is False:
self._errors['__all__'] = self.error_class([_(
'Failover needs to be disabled to perform network '
'changes.'
)])
except:
log.warn('Failed to verify failover status', exc_info=True)
ipv4key = 'int_ipv4address'
ipv4addr = cdata.get(ipv4key)
ipv4addr_b = cdata.get('int_ipv4address_b')
ipv4net = cdata.get("int_v4netmaskbit")
if ipv4addr and ipv4addr_b and ipv4net:
network = IPNetwork('%s/%s' % (ipv4addr, ipv4net))
if not network.overlaps(
IPNetwork('%s/%s' % (ipv4addr_b, ipv4net))
):
self._errors['int_ipv4address_b'] = self.error_class([
_('The IP must be within the same network')
])
ipv6addr = cdata.get("int_ipv6address")
ipv6net = cdata.get("int_v6netmaskbit")
ipv4 = True if ipv4addr and ipv4net else False
ipv6 = True if ipv6addr and ipv6net else False
# IF one field of ipv4 is entered, require the another
if (ipv4addr or ipv4net) and not ipv4:
if not (ipv4addr or ipv4addr_b) and not self._errors.get(ipv4key):
self._errors[ipv4key] = self.error_class([
_("You have to specify IPv4 address as well"),
])
if not ipv4net and 'int_v4netmaskbit' not in self._errors:
self._errors['int_v4netmaskbit'] = self.error_class([
_("You have to choose IPv4 netmask as well"),
])
# IF one field of ipv6 is entered, require the another
if (ipv6addr or ipv6net) and not ipv6:
if not ipv6addr and not self._errors.get('int_ipv6address'):
self._errors['int_ipv6address'] = self.error_class([
_("You have to specify IPv6 address as well"),
])
if not ipv6net:
self._errors['int_v6netmaskbit'] = self.error_class([
_("You have to choose IPv6 netmask as well"),
])
vip = cdata.get("int_vip")
dhcp = cdata.get("int_dhcp")
if not dhcp:
if vip and not ipv4addr_b:
self._errors['int_ipv4address_b'] = self.error_class([
_("This field is required for failover")
])
if vip and not ipv4addr:
self._errors['int_ipv4address'] = self.error_class([
_("This field is required for failover")
])
else:
cdata['int_ipv4address'] = ''
cdata['int_v4netmaskbit'] = ''
# API backward compatibility
options = cdata.get('int_options')
if options:
reg = RE_MTU.search(options)
if reg:
cdata['int_mtu'] = int(reg.group(1))
cdata['int_options'] = options.replace(reg.group(0), '')
return cdata