本文整理汇总了Python中netaddr.IPNetwork.iter_hosts方法的典型用法代码示例。如果您正苦于以下问题:Python IPNetwork.iter_hosts方法的具体用法?Python IPNetwork.iter_hosts怎么用?Python IPNetwork.iter_hosts使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netaddr.IPNetwork
的用法示例。
在下文中一共展示了IPNetwork.iter_hosts方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _add_search_filters
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def _add_search_filters(filters, query):
"""
Add Search Service response to filters
"""
search_query = query
# Try to parse IP/CIDR search
if IP_CIDR_RE.match(query):
try:
network = IPNetwork(query)
if network.size <= 4096:
search_query = ' '.join([str(host) for host in network.iter_hosts()])
search_query = search_query if search_query else query
except (AttributeError, IndexError, AddrFormatError, AddrConversionError):
pass
try:
reports = ImplementationFactory.instance.get_singleton_of('SearchServiceBase').search_reports(search_query)
if not reports:
reports = [None]
except SearchServiceException:
return
if 'in' in filters['where']:
for field in filters['where']['in']:
for key, values in field.iteritems():
if key == 'id' and len(values):
reports.extend(values)
filters['where']['in'].remove({key: values})
filters['where']['in'].append({'id': list(set(reports))})
else:
filters['where']['in'] = [{'id': reports}]
示例2: Subnets
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
class Subnets(object):
def __init__(self,subnet):
self.subnet = subnet
self.pefix = IPNetwork(self.subnet)
@property
def prefix(self):
return self.pefix
@property
def hosts(self):
return self.pefix.iter_hosts()
@property
def netmask(self):
return self.pefix.netmask
@property
def sub_network(self):
return self.pefix.network
@property
def range(self):
ip_list = list(self.hosts)
range = str(ip_list[0]) + '#' + str(len(ip_list))
return range
@property
def range2(self):
ip_list = list(self.hosts)
# vmware adds to the first given ip for count of IP's
count = len(ip_list) - 2
range = str(ip_list[2]) + '#' + str(count)
return range
示例3: Subnets
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
class Subnets(object):
def __init__(self,subnet):
self.subnet = subnet
self.pefix = IPNetwork(self.subnet)
@property
def prefix(self):
return self.pefix
@property
def hosts(self):
return self.pefix.iter_hosts()
@property
def netmask(self):
return self.pefix.netmask
@property
def sub_network(self):
return self.pefix.network
@property
def range(self):
ip_list = list(self.hosts)
range = str(ip_list[0]) + '#' + str(len(ip_list))
return range
示例4: _validateLoopbackPrefix
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def _validateLoopbackPrefix(self, pod, podDict, inventoryData):
inventoryDeviceCount = len(inventoryData['spines']) + len(inventoryData['leafs'])
lo0Block = IPNetwork(podDict['loopbackPrefix'])
lo0Ips = list(lo0Block.iter_hosts())
availableIps = len(lo0Ips)
if availableIps < inventoryDeviceCount:
raise ValueError("Pod[id='%s', name='%s']: loopbackPrefix available IPs %d not enough: required %d" % (pod.id, pod.name, availableIps, inventoryDeviceCount))
示例5: reserve_ip_addr
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def reserve_ip_addr(self):
"""Picks first available IP address from weave network.
If there's no available IP address anymore, ``IndexError``
will be raised. To prevent this error, catch the exception
or checks the value ``GluuCluster.ip_addr_available`` first
before trying to call this method.
:returns: A 2-elements tuple consists of IP address and network prefix,
e.g. ``("10.10.10.1", 24)``.
"""
# represents a pool of IP addresses
pool = IPNetwork(self.weave_ip_network)
# a generator holds possible IP addresses range, excluding exposed weave IP
ip_range = IPSet(pool.iter_hosts()) ^ IPSet(self.reserved_ip_addrs) ^ IPSet([self.exposed_weave_ip[0]])
# retrieves first IP address from ``ip_range`` generator
ip_addr = list(itertools.islice(ip_range, 1))[0]
# register the IP address so it will be excluded
# from possible IP range in subsequent requests
self.reserved_ip_addrs.append(str(ip_addr))
# weave IP address for container expects a traditional CIDR,
# e.g. 10.10.10.1/24, hence we return the actual IP and
# its prefix length
return str(ip_addr), pool.prefixlen
示例6: populateDhcpGlobalSettings
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def populateDhcpGlobalSettings(self):
ztp = {}
ztpGlobalSettings = util.loadClosDefinition()['ztp']
subnet = ztpGlobalSettings['dhcpSubnet']
dhcpBlock = IPNetwork(subnet)
ipList = list(dhcpBlock.iter_hosts())
ztp['network'] = str(dhcpBlock.network)
ztp['netmask'] = str(dhcpBlock.netmask)
ztp['defaultRoute'] = ztpGlobalSettings.get('dhcpOptionRoute')
if ztp['defaultRoute'] is None or ztp['defaultRoute'] == '':
ztp['defaultRoute'] = str(ipList[0])
ztp['rangeStart'] = ztpGlobalSettings.get('dhcpOptionRangeStart')
if ztp['rangeStart'] is None or ztp['rangeStart'] == '':
ztp['rangeStart'] = str(ipList[1])
ztp['rangeEnd'] = ztpGlobalSettings.get('dhcpOptionRangeEnd')
if ztp['rangeEnd'] is None or ztp['rangeEnd'] == '':
ztp['rangeEnd'] = str(ipList[-1])
ztp['broadcast'] = str(dhcpBlock.broadcast)
ztp['httpServerIp'] = self.conf['httpServer']['ipAddr']
ztp['imageUrl'] = ztpGlobalSettings.get('junosImage')
return ztp
示例7: _validateLoopbackPrefix
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def _validateLoopbackPrefix(self, pod, podDict, inventoryData):
inventoryDeviceCount = len(inventoryData['spines']) + len(inventoryData['leafs'])
lo0Block = IPNetwork(podDict['loopbackPrefix'])
lo0Ips = list(lo0Block.iter_hosts())
availableIps = len(lo0Ips)
cidr = 32 - int(math.ceil(math.log(inventoryDeviceCount, 2)))
if availableIps < inventoryDeviceCount:
raise InsufficientLoopbackIp("Pod[id='%s', name='%s']: loopbackPrefix minimum required: %s/%d" % (pod.id, pod.name, lo0Block.ip, cidr))
示例8: _allocateLoopback
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def _allocateLoopback(self, session, pod, loopbackPrefix, devices):
loopbackIp = IPNetwork(loopbackPrefix).network
numOfIps = len(devices) + 2 # +2 for network and broadcast
numOfBits = int(math.ceil(math.log(numOfIps, 2)))
cidr = 32 - numOfBits
lo0Block = IPNetwork(str(loopbackIp) + "/" + str(cidr))
lo0Ips = list(lo0Block.iter_hosts())
pod.allocatedLoopbackBlock = str(lo0Block.cidr)
self._assignAllocatedLoopbackToDevices(session, devices, lo0Ips)
示例9: targets
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def targets(self, targets):
# Always append, never overwrite.
# Fix target URLs if the scheme part is missing.
# Make sure self._targets contains a list.
self._targets = getattr(self, "_targets", [])
# Ignore the trivial case.
if not targets:
return
# Strip whitespace.
targets = [
x.strip()
for x in targets
if x not in self._targets
]
# Remove duplicates.
targets = [
x
for x in set(targets)
if x not in self._targets
]
# Encode all Unicode strings as UTF-8.
targets = [
x.encode("UTF-8") if isinstance(x, unicode) else str(x)
for x in targets
if x not in self._targets
]
# Detect network ranges, like 30.30.30.0/24, and get all IPs on it.
parsed_targets = []
for host in targets:
# Try to parse the address as a network range.
try:
tmp_target = IPNetwork(host)
except:
parsed_targets.append(host)
continue
# If it's a range, iterate it and get all IP addresses.
# If it's a single IP address, just add it.
if tmp_target.size != 1:
parsed_targets.extend(
str(x) for x in tmp_target.iter_hosts()
)
else:
parsed_targets.append( str(tmp_target.ip) )
# Add the new targets.
self._targets.extend(parsed_targets)
示例10: allocateLoopback
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def allocateLoopback(self, pod, loopbackPrefix, devices):
numOfIps = len(devices) + 2 # +2 for network and broadcast
numOfBits = int(math.ceil(math.log(numOfIps, 2)))
cidr = 32 - numOfBits
lo0Block = IPNetwork(loopbackPrefix + "/" + str(cidr))
lo0Ips = list(lo0Block.iter_hosts())
interfaces = []
pod.allocatedLoopbackBlock = str(lo0Block.cidr)
for device in devices:
ifl = InterfaceLogical('lo0.0', device, str(lo0Ips.pop(0)) + '/32')
interfaces.append(ifl)
self.dao.createObjects(interfaces)
示例11: scanIPclosed
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def scanIPclosed(self,result):
if result[0]:
# scan subnet outside ipv4.address/24
if result[1] == "address":
print "[Networkbrowser] got IP:",result[0]
self.setStatus('update')
net = IPNetwork('%s/24' % result[0])
localnet = IPNetwork('%s/%s' % (self._ipv4.address, self._ipv4.netmask))
if localnet.__contains__(net):
self._startScan(self.iface, net.cidr)
else:
for host in net.iter_hosts():
self._nrthreads += 1
reactor.callInThread(self.getNetworkIPs, str(host))
# add offline host
elif result[1] == "nfs":
self.networklist.append(NetworkItemHost(result[0], result[0], ['nfs']))
write_cache(self.cache_file, self.networklist)
self.updateNetworkList()
示例12: __init__
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def __init__(self, params):
BasePayload.__init__(self, params)
try:
from netaddr import IPNetwork
from netaddr.core import AddrFormatError
net = IPNetwork(u'%s' % self.params["net"])
self.f = net.iter_hosts()
self.__count = net.size - 2
if self.__count <= 0:
raise FuzzExceptPluginBadParams("There are not hosts in the specified network")
except AddrFormatError:
raise FuzzExceptPluginBadParams("The specified network has an incorrect format.")
except ValueError:
raise FuzzExceptPluginBadParams("The specified network has an incorrect format.")
except ImportError:
raise FuzzExceptBadInstall("ipnet plugin requires netaddr module. Please install it using pip.")
示例13: Controller
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
#.........这里部分代码省略.........
self.__reservation_logger)}
self.__reservation_map['manager'].start()
self.__force_terminate_lock = Lock()
self.config_parser = config_parser
self.__created_nodes = []
self.__partially_created_nodes = []
self.__available_clouds = []
self.__default_cloud = None
if config_parser.has_option('iaas', 'DRIVER'):
self.__default_cloud = iaas.get_cloud_instance(
'iaas',
config_parser.get('iaas', 'DRIVER').lower(),
config_parser)
self.__available_clouds.append(self.__default_cloud)
if config_parser.has_option('iaas', 'OTHER_CLOUDS'):
self.__logger.debug("attempt iaas.get_clouds()")
try:
self.__available_clouds.extend(iaas.get_clouds(config_parser))
except Exception as e:
self.__logger.debug("failed iaas.get_clouds()")
self.__reservation_map['manager'].stop()
raise e
self.__logger.debug("succeeded iaas.get_clouds()")
# Setting VM role
self.role = 'agent'
def get_available_ipop_address(self):
"""Return an unassigned IP address in this manager's VPN subnet"""
# Network iterator
network = self.__ipop_subnet.iter_hosts()
# Currently running hosts
running_hosts = [ str(node.ip)
for node in self.__created_nodes + self.__partially_created_nodes ]
self.__logger.debug("get_available_ipop_address: running nodes: %s"
% running_hosts)
# The first address is used by IPOP internally
network.next()
# The second one is taken by manager
network.next()
for host in network:
host = str(host)
if host not in running_hosts:
self.__logger.debug("get_available_ipop_address: returning %s"
% host)
return host
#=========================================================================#
# create_nodes(self, count, contextFile, test_agent) #
#=========================================================================#
def create_nodes(self, count, test_agent, port, cloud=None, inst_type=None):
"""
Creates the VMs associated with the list of nodes. It also tests
if the agents started correctly.
@param count The number of nodes to be created
@param test_agent A callback function to test if the agent
示例14: get_random_ip
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def get_random_ip(cidr):
net = IPNetwork(cidr)
ip_list = list(net.iter_hosts())
index = random.randint(0, len(ip_list) - 1)
return str(ip_list[index])
示例15: add_targets
# 需要导入模块: from netaddr import IPNetwork [as 别名]
# 或者: from netaddr.IPNetwork import iter_hosts [as 别名]
def add_targets(self, audit_config, dns_resolution = 1):
# Validate the arguments.
if dns_resolution not in (0, 1, 2):
raise ValueError(
"Argument 'dns_resolution' can only be 0, 1 or 2,"
" got %r instead" % dns_resolution)
# Remember if subdomains are allowed.
include_subdomains = audit_config.include_subdomains
# We'll remember here what *new* domains were added, for IP resolution.
new_domains = set()
# For each user-supplied target string...
for target in audit_config.targets:
target = to_utf8(target)
# If it's an IP address...
try:
# For IPv6 address
if target.startswith("[") and target.endswith("]"):
IPAddress(target[1:-1], version=6)
address = target[1:-1]
else:
# IPv4
IPAddress(target)
address = target
except Exception:
##raise # XXX DEBUG
address = None
if address is not None:
# Keep the IP address.
self.__addresses.add(address)
# If it's an IP network...
else:
try:
network = IPNetwork(target)
except Exception:
##raise # XXX DEBUG
network = None
if network is not None:
# For each host IP address in range...
for address in network.iter_hosts():
address = str(address)
# Keep the IP address.
self.__addresses.add(address)
# If it's a domain name...
elif self._re_is_domain.match(target):
# Convert it to lowercase.
target = target.lower()
# Is the domain new?
if target not in self.__domains:
# Keep the domain name.
self.__domains.add(target)
new_domains.add(target)
# If it's an URL...
else:
try:
parsed_url = ParsedURL(target)
url = parsed_url.url
except Exception:
##raise # XXX DEBUG
url = None
if url is not None:
# Keep the URL.
self.__web_pages.add(url)
#ADD By BlackYe
self.__target_url.add(url)
# If we allow parent folders...
if audit_config.allow_parent:
# Add the base URL too.
self.__web_pages.add(parsed_url.base_url)
# Extract the domain or IP address.
host = parsed_url.host
try:
if host.startswith("[") and host.endswith("]"):
IPAddress(host[1:-1], version=6)
host = host[1:-1]
else:
IPAddress(host)
self.__addresses.add(host)
except Exception:
##raise # XXX DEBUG
host = host.lower()
if host not in self.__domains:
self.__domains.add(host)
new_domains.add(host)
#.........这里部分代码省略.........