本文整理汇总了Python中netaddr.IPRange方法的典型用法代码示例。如果您正苦于以下问题:Python netaddr.IPRange方法的具体用法?Python netaddr.IPRange怎么用?Python netaddr.IPRange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netaddr
的用法示例。
在下文中一共展示了netaddr.IPRange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_ip_ranges
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def parse_ip_ranges(iprangesconfig):
ipranges = netaddr.IPSet([])
iprangessplit = [i.strip() for i in iprangesconfig.split(",")]
for iprange in iprangessplit:
if not iprange:
continue
try:
if "-" in iprange:
spl = iprange.split("-", 1)
ipns = netaddr.IPRange(spl[0], spl[1])
elif "*" in iprange:
ipns = netaddr.IPGlob(iprange)
else:
ipns = netaddr.IPNetwork(iprange)
ipranges.add(ipns)
except:
pprint("Bad IP definition: %s" % iprangesconfig)
sys.exit()
return ipranges
示例2: main
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def main():
module = AnsibleModule(argument_spec=dict(
start=dict(required=True, type='str'),
end=dict(required=True, type='str'),
min_size=dict(required=True, type='int'),
))
start = module.params.get('start')
end = module.params.get('end')
iprange = netaddr.IPRange(start, end)
if len(iprange) < module.params.get('min_size'):
module.exit_json(
changed=True,
warnings=[
'The IP range {} - {} contains {} addresses.'.format(
start, end, len(iprange)),
'This might not be enough for the deployment or later scaling.'
])
else:
module.exit_json(msg='success')
示例3: pop_ip
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def pop_ip(provider_net):
"""Picks an ip from the provider_net
It will first take ips in the extra_ips if possible.
extra_ips is a list of isolated ips whereas ips described
by the [provider_net.start, provider.end] range is a continuous
list of ips.
"""
# Construct the pool of ips
extra_ips = provider_net.get('extra_ips', [])
if len(extra_ips) > 0:
ip = extra_ips.pop()
provider_net['extra_ips'] = extra_ips
return ip
ips = list(IPRange(provider_net['start'],
provider_net['end']))
# Get the next ip
ip = str(ips.pop())
# Remove this ip from the env
provider_net['end'] = str(ips.pop())
return ip
示例4: __init__
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def __init__(self, params):
BasePayload.__init__(self, params)
try:
from netaddr import IPRange
from netaddr.core import AddrFormatError
ran = self.params["iprange"].split("-")
net = IPRange(ran[0], ran[1])
self.f = iter(net)
self.__count = net.size
except ImportError:
raise FuzzExceptBadInstall("ipnet plugin requires netaddr module. Please install it using pip.")
except AddrFormatError:
raise FuzzExceptPluginBadParams("The specified network range has an incorrect format.")
except IndexError:
raise FuzzExceptPluginBadParams("The specified network range has an incorrect format.")
示例5: gen_subnet_size
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def gen_subnet_size(self):
labels = ['cloud', 'network_name']
net_size = Gauge('neutron_net_size',
'Neutron networks size',
labels, registry=self.registry)
for n in self.prodstack['networks']:
size = 0
for subnet in n['subnets']:
for pool in self.subnet_map[subnet]['pool']:
if ':' in pool['start']:
# Skip IPv6 address pools; they are big enough to
# drown the IPv4 numbers we might care about.
continue
size += IPRange(pool['start'], pool['end']).size
label_values = [config['cloud'], self.network_map[n['id']]]
net_size.labels(*label_values).set(size)
示例6: __init__
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def __init__(self, blacklist_string):
"""
Initialize a IPBlacklistEntry object based on the blacklist_string
argument.
:param blacklist_string: The string to build an IPBlacklistEntry object
from.
:return: None
"""
self._ip_string = blacklist_string[:blacklist_string.find(",")].strip()
self._range_name = blacklist_string[blacklist_string.find(",") + 1:].strip()
if "-" in self._ip_string:
range_start = self._ip_string[:self._ip_string.find("-")].strip()
range_end = self._ip_string[self._ip_string.find("-") + 1:].strip()
self._ip_range = IPRange(range_start, range_end)
else:
self._ip_range = IPNetwork(self._ip_string)
# Static Methods
# Class Methods
# Public Methods
示例7: find
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def find(self, search) -> Optional[MAASIPRange]:
"""Searches the list of IPRange objects until it finds the specified
search parameter, and returns the range it belongs to if found.
(If the search parameter is a range, returns the result based on
matching the searching for the range containing the first IP address
within that range.)
"""
if isinstance(search, IPRange):
for item in self.ranges:
if (
item.first <= search.first <= item.last
and item.first <= search.last <= item.last
):
return item
else:
addr = IPAddress(search)
addr = int(addr)
for item in self.ranges:
if item.first <= addr <= item.last:
return item
return None
示例8: make_iprange
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def make_iprange(first, second=None, purpose="unknown") -> MAASIPRange:
"""Returns a MAASIPRange (which is compatible with IPRange) for the
specified range of addresses.
:param second: the (inclusive) upper bound of the range. If not supplied,
uses the lower bound (creating a range of 1 address).
:param purpose: If supplied, stores a comment in the range object to
indicate the purpose of this range.
"""
if isinstance(first, int):
first = IPAddress(first)
if second is None:
second = first
else:
if isinstance(second, int):
second = IPAddress(second)
iprange = MAASIPRange(inet_ntop(first), inet_ntop(second), purpose=purpose)
return iprange
示例9: test_contains_method
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def test_contains_method(self):
s = MAASIPSet(
[
make_iprange("10.0.0.1", "10.0.0.100"),
make_iprange("10.0.0.200", "10.0.0.254"),
]
)
self.assertThat(s, Contains("10.0.0.1"))
self.assertThat(s, Contains(IPAddress("10.0.0.1")))
self.assertThat(s, Contains(IPRange("10.0.0.1", "10.0.0.100")))
self.assertThat(s, Not(Contains(IPRange("10.0.0.1", "10.0.0.101"))))
self.assertThat(s, Not(Contains("10.0.0.101")))
self.assertThat(s, Not(Contains("10.0.0.199")))
self.assertThat(s, Contains(IPRange("10.0.0.200", "10.0.0.254")))
self.assertThat(s, Not(Contains(IPRange("10.0.0.99", "10.0.0.254"))))
self.assertThat(s, Not(Contains("10.0.0.255")))
示例10: test_normalizes_range_with_iprange
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def test_normalizes_range_with_iprange(self):
addr1 = "10.0.0.1"
addr2 = IPAddress("10.0.0.2")
range1 = make_iprange("10.0.0.3", purpose="DNS")
range2 = IPRange("10.0.0.4", "10.0.0.100")
s = MAASIPSet([range2, range1, addr1, addr2])
for item in s:
self.assertThat(type(item), Equals(MAASIPRange))
self.assertThat(s, Contains("10.0.0.1"))
self.assertThat(s, Contains("10.0.0.2"))
self.assertThat(s, Contains("10.0.0.3"))
self.assertThat(s, Contains("10.0.0.4"))
self.assertThat(s, Contains("10.0.0.50"))
self.assertThat(s, Contains("10.0.0.100"))
self.assertThat(s, Not(Contains("10.0.0.101")))
self.assertThat(s, Not(Contains("10.0.0.0")))
示例11: test_excplicitly
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def test_excplicitly(self):
# The other tests in this TestCase rely on
# get_expected_generate_directives(), which is quite dense. Here
# we test get_GENERATE_directives() explicitly.
ip_range = IPRange("192.168.0.55", "192.168.2.128")
expected_directives = [
("55-255", "$.0.168.192.in-addr.arpa.", "192-168-0-$.domain."),
("0-255", "$.1.168.192.in-addr.arpa.", "192-168-1-$.domain."),
("0-128", "$.2.168.192.in-addr.arpa.", "192-168-2-$.domain."),
]
self.assertItemsEqual(
expected_directives,
DNSReverseZoneConfig.get_GENERATE_directives(
ip_range,
domain="domain",
zone_info=DomainInfo(
IPNetwork("192.168.0.0/16"), "168.192.in-addr.arpa"
),
),
)
示例12: ip_set_from_address_range
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def ip_set_from_address_range(start, end):
try:
start_ip_address = ip_address_from_address(start)
end_ip_address = ip_address_from_address(end)
except (NotSupported, ValueError) as e:
raise ValueError(
('invalid IP range: %(start)s-%(end)s (%(message)s)') %
{
'start': start,
'end': end,
'message': e.message})
except netaddr.AddrFormatError as e:
raise ValueError(
("invalid IP range: '%(start)s-%(end)s' (%(message)s)") %
{
'start': start,
'end': end,
'message': e.message})
if start_ip_address > end_ip_address:
raise ValueError(
('invalid IP range: %(start)s-%(end)s (lower bound IP greater than'
' upper bound)') %
{
'start': start,
'end': end})
ip_range = netaddr.IPRange(start_ip_address, end_ip_address)
return netaddr.IPSet(ip_range)
示例13: parse_targets
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def parse_targets(target):
if '-' in target:
ip_range = target.split('-')
try:
t = IPRange(ip_range[0], ip_range[1])
except AddrFormatError:
try:
start_ip = IPAddress(ip_range[0])
start_ip_words = list(start_ip.words)
start_ip_words[-1] = ip_range[1]
start_ip_words = [str(v) for v in start_ip_words]
end_ip = IPAddress('.'.join(start_ip_words))
t = IPRange(start_ip, end_ip)
except AddrFormatError:
t = target
else:
try:
t = IPNetwork(target)
except AddrFormatError:
t = target
if type(t) == IPNetwork or type(t) == IPRange:
return list(t)
else:
return [t.strip()]
示例14: _translate_ip_ranges
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def _translate_ip_ranges(indicator, value=None):
if value is not None and value['type'] != 'IPv4':
return [indicator]
try:
ip_range = IPRange(*indicator.split('-', 1))
except (AddrFormatError, ValueError, TypeError):
return [indicator]
return [str(x) if x.size != 1 else str(x.network) for x in ip_range.cidrs()]
示例15: _stix_ip_observable
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPRange [as 别名]
def _stix_ip_observable(namespace, indicator, value):
category = cybox.objects.address_object.Address.CAT_IPV4
if value['type'] == 'IPv6':
category = cybox.objects.address_object.Address.CAT_IPV6
indicators = [indicator]
if '-' in indicator:
# looks like an IP Range, let's try to make it a CIDR
a1, a2 = indicator.split('-', 1)
if a1 == a2:
# same IP
indicators = [a1]
else:
# use netaddr builtin algo to summarize range into CIDR
iprange = netaddr.IPRange(a1, a2)
cidrs = iprange.cidrs()
indicators = map(str, cidrs)
observables = []
for i in indicators:
id_ = '{}:observable-{}'.format(
namespace,
uuid.uuid4()
)
ao = cybox.objects.address_object.Address(
address_value=i,
category=category
)
o = cybox.core.Observable(
title='{}: {}'.format(value['type'], i),
id_=id_,
item=ao
)
observables.append(o)
return observables