本文整理汇总了Python中netaddr.iter_iprange方法的典型用法代码示例。如果您正苦于以下问题:Python netaddr.iter_iprange方法的具体用法?Python netaddr.iter_iprange怎么用?Python netaddr.iter_iprange使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netaddr
的用法示例。
在下文中一共展示了netaddr.iter_iprange方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_subnet_addr_generator
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def _init_subnet_addr_generator(self, subnet_id, subnet):
def ip_generator(ip_list):
for ip in ip_list:
yield ip
if not subnet:
self._subnets[subnet_id] = ip_generator([])
allocation_pools = subnet.get('allocation_pools', None)
for pool in allocation_pools:
start = pool['start']
end = pool['end']
ip_list = list(str(ip) for ip in
netaddr.iter_iprange(start, end))
self._subnets[subnet_id] = ip_generator(
[ip for ip in ip_list])
示例2: set_used_ips
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def set_used_ips(user_defined_config, inventory):
"""Set all of the used ips into a global list.
:param user_defined_config: ``dict`` User defined configuration
:param inventory: ``dict`` Living inventory of containers and hosts
"""
used_ips = user_defined_config.get('used_ips')
if isinstance(used_ips, list):
for ip in used_ips:
split_ip = ip.split(',')
if len(split_ip) >= 2:
ip_range = list(
netaddr.iter_iprange(
split_ip[0],
split_ip[-1]
)
)
USED_IPS.update([str(i) for i in ip_range])
else:
logger.debug("IP %s set as used", split_ip[0])
USED_IPS.add(split_ip[0])
# Find all used IP addresses and ensure that they are not used again
for host_entry in inventory['_meta']['hostvars'].values():
networks = host_entry.get('container_networks', dict())
for network_entry in networks.values():
address = network_entry.get('address')
if address:
logger.debug("IP %s set as used", address)
USED_IPS.add(address)
示例3: gen_mako_macro
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def gen_mako_macro():
return '''<%
import netaddr
from itertools import islice
it = netaddr.iter_iprange('100.0.0.0','160.0.0.0')
def gen_paths(num):
return list('{0}/32'.format(ip) for ip in islice(it, num))
%>
'''
示例4: _set_used_ips
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def _set_used_ips(user_defined_config, inventory):
"""Set all of the used ips into a global list.
:param user_defined_config: ``dict`` User defined configuration
:param inventory: ``dict`` Living inventory of containers and hosts
"""
used_ips = user_defined_config.get('used_ips')
if isinstance(used_ips, list):
for ip in used_ips:
split_ip = ip.split(',')
if len(split_ip) >= 2:
ip_range = list(
netaddr.iter_iprange(
split_ip[0],
split_ip[-1]
)
)
USED_IPS.extend([str(i) for i in ip_range])
else:
append_if(array=USED_IPS, item=split_ip[0])
# Find all used IP addresses and ensure that they are not used again
for host_entry in inventory['_meta']['hostvars'].values():
if 'ansible_ssh_host' in host_entry:
append_if(array=USED_IPS, item=host_entry['ansible_ssh_host'])
for key, value in host_entry.iteritems():
if key.endswith('address'):
append_if(array=USED_IPS, item=value)
示例5: _gen_interface_ip_lists
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def _gen_interface_ip_lists(cfg):
interface_ip_lists = {}
interfaces = cfg.get_interfaces()
for interface in interfaces:
label = interface.label
ip_list_prelim = []
ip_list = []
if 'address_list' in interface.keys():
ip_list_prelim = interface.address_list
elif 'IPADDR_list' in interface.keys():
ip_list_prelim = interface.IPADDR_list
for ip in ip_list_prelim:
if '-' in ip:
ip_range = ip.split('-')
for _ip in iter_iprange(ip_range[0], ip_range[1]):
ip_list.append(str(_ip))
else:
ip_list.append(ip)
if 'address_start' in interface.keys():
ip_list = [IPAddress(interface.address_start)]
elif 'IPADDR_start' in interface.keys():
ip_list = [IPAddress(interface.IPADDR_start)]
interface_ip_lists[label] = ip_list
return interface_ip_lists
示例6: _parse_iprange
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def _parse_iprange(self, range):
try:
if '-' in range:
return list(netaddr.iter_iprange(*range.split('-')))
else:
return list(netaddr.IPNetwork(range))
except netaddr.core.AddrFormatError:
return
示例7: prepare_scope
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def prepare_scope(scope_file,expanded_scope):
"""Parse IP ranges inside the provided scope file to expand IP ranges. This supports ranges
with hyphens, underscores, and CIDRs.
Parameters:
scope_file A file containing domain name and IP addresses/ranges
expanded_scope A list object for storing to expanded scope list
"""
try:
with open(scope_file,"r") as scope_file:
for target in scope_file:
target = target.rstrip()
# Record individual IPs and expand CIDRs
if helpers.is_ip(target):
ip_list = list(IPNetwork(target))
for address in sorted(ip_list):
str_address = str(address)
expanded_scope.append(str_address)
# Sort IP ranges from domain names and expand the ranges
if not helpers.is_domain(target):
# Check for hyphenated ranges like those accepted by Nmap, e.g. 192.168.1.1-50
if "-" in target:
target = target.rstrip()
parts = target.split("-")
startrange = parts[0]
b = parts[0]
dot_split = b.split(".")
temp = "."
# Join the values using a "." so it makes a valid IP
combine = dot_split[0],dot_split[1],dot_split[2],parts[1]
endrange = temp.join(combine)
# Calculate the IP range
ip_list = list(iter_iprange(startrange,endrange))
# Iterate through the range and remove ip_list
for x in ip_list:
temp = str(x)
expanded_scope.append(temp)
# Check if range has an underscore, e.g. 192.168.1.2_192.168.1.155
elif "_" in target:
target = target.rstrip()
parts = target.split("_")
startrange = parts[0]
endrange = parts[1]
ip_list = list(iter_iprange(startrange,endrange))
for address in ip_list:
str_address = str(address)
expanded_scope.append(str_address)
else:
expanded_scope.append(target.rstrip())
click.secho("[+] Scope list expanded to {} items. Proceeding with verification \
checks.".format(len(expanded_scope)),fg="green")
except IOError as error:
click.secho("[!] Parsing of scope file failed!",fg="red")
click.secho("L.. Details: {}".format(error),fg="red")
示例8: generate_scope
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def generate_scope(scope_file):
"""Parse IP ranges inside the provided scope file to expand IP ranges. This supports ranges
with hyphens, underscores, and CIDRs.
Parameters:
scope_file A file containing domain names and IP addresses/ranges
"""
scope = []
try:
with open(scope_file,"r") as scope_file:
for target in scope_file:
target = target.rstrip()
# Record individual IPs and expand CIDRs
if is_ip(target):
ip_list = list(IPNetwork(target))
for address in sorted(ip_list):
str_address = str(address)
scope.append(str_address)
# Sort IP ranges from domain names and expand the ranges
if not is_domain(target):
# Check for hyphenated ranges like those accepted by Nmap
# Ex: 192.168.1.1-50 will become 192.168.1.1 ... 192.168.1.50
if "-" in target:
target = target.rstrip()
parts = target.split("-")
startrange = parts[0]
b = parts[0]
dot_split = b.split(".")
temp = "."
# Join the values using a "." so it makes a valid IP
combine = dot_split[0],dot_split[1],dot_split[2],parts[1]
endrange = temp.join(combine)
# Calculate the IP range
ip_list = list(iter_iprange(startrange,endrange))
# Iterate through the range and remove ip_list
for x in ip_list:
temp = str(x)
scope.append(temp)
# Check if range has an underscore because underscores are fine, I guess?
# Ex: 192.168.1.2_192.168.1.155
elif "_" in target:
target = target.rstrip()
parts = target.split("_")
startrange = parts[0]
endrange = parts[1]
ip_list = list(iter_iprange(startrange,endrange))
for address in ip_list:
str_address = str(address)
scope.append(str_address)
else:
scope.append(target.rstrip())
except IOError as error:
click.secho("[!] Parsing of scope file failed!",fg="red")
click.secho("L.. Details: {}".format(error),fg="red")
return scope
示例9: _create_switch_lports
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def _create_switch_lports(self, lswitch, lport_create_args = [],
lport_amount=1, lport_ip_shift = 1):
LOG.info("create %d lports on lswitch %s" % \
(lport_amount, lswitch["name"]))
self.RESOURCE_NAME_FORMAT = "lpXXXXXX_XXXXXX"
batch = lport_create_args.get("batch", lport_amount)
port_security = lport_create_args.get("port_security", True)
LOG.info("Create lports method: %s" % self.install_method)
network_cidr = lswitch.get("cidr", None)
ip_addrs = None
if network_cidr:
end_ip = network_cidr.ip + lport_amount + lport_ip_shift
if not end_ip in network_cidr:
message = _("Network %s's size is not big enough for %d lports.")
raise exceptions.InvalidConfigException(
message % (network_cidr, lport_amount))
ip_addrs = netaddr.iter_iprange(network_cidr.ip + lport_ip_shift,
network_cidr.last)
ovn_nbctl = self._get_ovn_controller(self.install_method)
ovn_nbctl.enable_batch_mode()
base_mac = [i[:2] for i in self.task["uuid"].split('-')]
base_mac[0] = str(hex(int(base_mac[0], 16) & 254))
base_mac[3:] = ['00']*3
flush_count = batch
lports = []
for i in range(lport_amount):
ip = str(next(ip_addrs)) if ip_addrs else ""
if len(ip):
name = "lp_%s" % ip
else:
name = self.generate_random_name()
mac = utils.get_random_mac(base_mac)
ip_mask = '{}/{}'.format(ip, network_cidr.prefixlen)
gw = str(self._get_gw_ip(network_cidr))
lport = ovn_nbctl.lswitch_port_add(lswitch["name"], name, mac,
ip_mask, gw)
ovn_nbctl.lport_set_addresses(name, [mac, ip])
if port_security:
ovn_nbctl.lport_set_port_security(name, mac)
lports.append(lport)
flush_count -= 1
if flush_count < 1:
ovn_nbctl.flush()
flush_count = batch
ovn_nbctl.flush() # ensure all commands be run
ovn_nbctl.enable_batch_mode(False)
return lports
示例10: main
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import iter_iprange [as 别名]
def main():
module = AnsibleModule(
argument_spec=dict(
start_cidr=dict(required=True),
num_emulation_hosts=dict(required=False, default="null"),
num_ip=dict(required=True)
),
supports_check_mode=True
)
start_cidr = module.params['start_cidr']
num_emulation_hosts = module.params['num_emulation_hosts']
num_ip = module.params['num_ip']
sandbox_cidr = netaddr.IPNetwork(start_cidr)
sandbox_hosts = netaddr.iter_iprange(sandbox_cidr.ip, sandbox_cidr.last)
ip_data = t_ip_data()
chassis_per_host = int(num_ip) / int(num_emulation_hosts)
overflow = 0
for i in range(0, int(num_ip)):
'''
cidr = start_cidr_ip.split('.')[0] + "." + \
start_cidr_ip.split('.')[1] + "." + \
start_cidr_ip.split('.')[2] + "." + \
str(int(start_cidr_ip.split('.')[3]) + i)
'''
# ip_data.index.append(i % int(num_emulation_hosts))
index = i / chassis_per_host
if (index >= int(num_emulation_hosts)):
index = int(num_emulation_hosts) - 1
overflow += 1
ip_data.index.append(index)
ip_data.ip_list.append(str(sandbox_hosts.next()))
farm_data = t_farm_data()
num_sandbox = 0
sandbox_hosts = netaddr.iter_iprange(sandbox_cidr.ip, sandbox_cidr.last)
for i in range(0, int(num_emulation_hosts)):
farm_data.farm_index.append(i)
num_sandbox = chassis_per_host
if (i == int(num_emulation_hosts) - 1):
num_sandbox = chassis_per_host + overflow
farm_data.num_sandbox_farm.append(num_sandbox)
farm_data.start_cidr_farm.append(str(sandbox_hosts.next()))
for i in range (0, num_sandbox - 1):
sandbox_hosts.next()
module.exit_json(changed=True,ip_index=ip_data.index, \
ip_index_list=str(ip_data.ip_list), \
prefixlen=str(sandbox_cidr.prefixlen),
farm_index=farm_data.farm_index,
num_sandbox_farm=farm_data.num_sandbox_farm,
start_cidr_farm=farm_data.start_cidr_farm)
# import module snippets