本文整理汇总了Python中netaddr.iter_iprange函数的典型用法代码示例。如果您正苦于以下问题:Python iter_iprange函数的具体用法?Python iter_iprange怎么用?Python iter_iprange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iter_iprange函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: is_match_ip_space
def is_match_ip_space(self, ip_addr, ip_space):
"""
Passed an IP address and an IP address space and check
if the IP address belongs to the IP address space.
If it does return 1 otherwise return 0
"""
#*** Does ip_space look like a CIDR network?:
if "/" in ip_space:
try:
ip_space_object = IPNetwork(ip_space)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.logger.error("error=E1000015 "
"Exception converting to IPNetwork object. "
"Exception %s, %s, %s",
exc_type, exc_value, exc_traceback)
return 0
#*** Does it look like an IP range?:
elif "-" in ip_space:
ip_range = ip_space.split("-")
if len(ip_range) != 2:
self.logger.error("error=E1000016 "
"Range split of ip_space %s on - was not len 2 but %s",
ip_space, len(ip_range))
return 0
try:
ip_space_object = list(iter_iprange(ip_range[0], ip_range[1]))
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.logger.error("error=E1000017 "
"Exception on conversion of %s to iter_iprange "
"Exception %s, %s, %s",
ip_range, exc_type, exc_value, exc_traceback)
return 0
else:
#*** Or is it just a plain simple IP address?:
try:
ip_space_object = list(iter_iprange(ip_space, ip_space))
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.logger.error("error=E1000019 "
"Exception converting to IPAddress object. "
"Exception %s, %s, %s",
exc_type, exc_value, exc_traceback)
return 0
#*** Convert the IP address to a netaddr IPAddress object:
try:
ip_addr_object = IPAddress(ip_addr)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
self.logger.error("error=E1000021 "
"Exception converting to IPAddress object. "
"Exception %s, %s, %s",
exc_type, exc_value, exc_traceback)
return 0
#*** Now we have both in netaddr form, so do the match comparison:
if ip_addr_object in ip_space_object:
return 1
else:
return 0
开发者ID:EnjoyHacking,项目名称:nmeta,代码行数:60,代码来源:tc_static.py
示例2: generate_scope
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
开发者ID:chrismaddalena,项目名称:viper,代码行数:55,代码来源:helpers.py
示例3: prepare_scope
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")
开发者ID:chrismaddalena,项目名称:viper,代码行数:54,代码来源:verification.py
示例4: get_subnet
def get_subnet(self, start='10.10.1.0', end='10.10.255.0', step=256):
subnet_gen = netaddr.iter_iprange(start, end, step=step)
i = 1
while True:
with self.lock:
try:
yield (i, str(subnet_gen.next()))
except StopIteration:
subnet_gen = netaddr.iter_iprange(start, end, step=step)
yield (i, str(subnet_gen.next()))
i += 1
开发者ID:openstack,项目名称:neutron-dynamic-routing,代码行数:11,代码来源:base.py
示例5: run
def run (self, tmp = None, task_vars = dict ()):
database_location = self._task.args.get ("database_location")
taken_addresses = set ()
for ip_path, ip_target \
in self.client.get_tree (database_location):
ip_name = ip_path [1:]
taken_addresses.add (ip_name)
address_range = (
netaddr.iter_iprange (
self._task.args.get ("start_address"),
self._task.args.get ("end_address")))
ip_address = next (
ip_address for ip_address in address_range
if not str (ip_address) in taken_addresses)
allocation_name = (
self._task.args.get ("name"))
self.client.create_raw (
"%s/%s" % (database_location, str (ip_address)),
allocation_name)
return dict (
changed = True,
address = ip_address)
开发者ID:wellbehavedsoftware,项目名称:gridlinker,代码行数:31,代码来源:network_address_allocator.py
示例6: _set_used_ips
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():
networks = host_entry.get('container_networks', dict())
for network_entry in networks.values():
address = network_entry.get('address')
if address:
append_if(array=USED_IPS, item=address)
开发者ID:conzetti,项目名称:openstack-ansible,代码行数:28,代码来源:dynamic_inventory.py
示例7: ip_range_to_cidr
def ip_range_to_cidr(ip_network_string):
"""Convert ip_network_string into CIDR notation."""
# Split string into list by ', ' delimiter.
ip_network_cidr = []
ip_network_list = ip_network_string.split(',')
for ip_object in ip_network_list:
# For every ip range ('10.182.71.0-10.182.75.255'), convert to individual slash notation, 10.182.71.0/24, 10.182.72.0/22.
if '-' in ip_object:
# The object is a range.
dash = ip_object.find('-')
# First part of ip range.
ip_start = ip_object[:dash]
# Last part of ip range.
ip_end = ip_object[dash + 1:]
# Generate lists of IP addresses in range.
ip_range = list(netaddr.iter_iprange(ip_start, ip_end))
# Convert start & finish range to CIDR.
ip_range = netaddr.cidr_merge(ip_range)
# May be one or more objects in list.
# Example 1: '10.182.71.0-10.182.75.255' ==> ['10.182.71.0/24, 10.182.72.0/22']
# Example 2: '10.182.90.0-10.182.91.255' ==> ['10.182.90.0/23']
# Add each CIDR to ip_network.
for ip_object in ip_range:
ip_network_cidr.append(str(ip_object))
else:
# The object is not a range, just add it.
logging.debug('ip_object = %s' % (ip_object))
ip_network_cidr.append(str(netaddr.IPNetwork(ip_object).cidr))
# Return as a string with delimiter ', '
return ip_network_cidr
开发者ID:paragbaxi,项目名称:qualysguard_vm_scan_dead_hosts,代码行数:30,代码来源:qualysguard_vm_scan_dead_hosts.py
示例8: test_ip_range
def test_ip_range():
ip_list = list(iter_iprange('192.0.2.1', '192.0.2.14'))
assert len(ip_list) == 14
assert ip_list == [
IPAddress('192.0.2.1'),
IPAddress('192.0.2.2'),
IPAddress('192.0.2.3'),
IPAddress('192.0.2.4'),
IPAddress('192.0.2.5'),
IPAddress('192.0.2.6'),
IPAddress('192.0.2.7'),
IPAddress('192.0.2.8'),
IPAddress('192.0.2.9'),
IPAddress('192.0.2.10'),
IPAddress('192.0.2.11'),
IPAddress('192.0.2.12'),
IPAddress('192.0.2.13'),
IPAddress('192.0.2.14'),
]
assert cidr_merge(ip_list) == [
IPNetwork('192.0.2.1/32'),
IPNetwork('192.0.2.2/31'),
IPNetwork('192.0.2.4/30'),
IPNetwork('192.0.2.8/30'),
IPNetwork('192.0.2.12/31'),
IPNetwork('192.0.2.14/32'),
]
开发者ID:drkjam,项目名称:netaddr,代码行数:30,代码来源:test_ip_ranges.py
示例9: checkIPRange
def checkIPRange(self,Ip1,Ip2):
try:
IPRange=list(netaddr.iter_iprange(Ip1, Ip2))
return IPAddress(self.ClientIp) in IPRange
except:
print self.ContentId+":An exception occured in checkIPRange function! Please check your ACL!"
return False
开发者ID:taskinegemen,项目名称:cloud,代码行数:7,代码来源:AccessCheck.py
示例10: main
def main():
module = AnsibleModule(
argument_spec=dict(
start_cidr=dict(required=True),
group_size=dict(required=False, default="null"),
num_ip=dict(required=True)
),
supports_check_mode=True
)
start_cidr = module.params['start_cidr']
group_size = module.params['group_size']
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()
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(group_size))
ip_data.ip_list.append(str(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))
开发者ID:l8huang,项目名称:ovn-scale-test,代码行数:32,代码来源:generate_chassis_ip_pairs.py
示例11: get_available_ip
def get_available_ip(name):
'''
Gets the next available IP in the subnet range.
NOTE: This could be improved!
It is slow and creates a list of all the IPs in the range as well as all of the used IPs
Runs a while loop through the generated IP list until it finds an address that is not used
Returns next available IP
arguments:
name: subnet_name
'''
subnet_info_obj = Subnet.objects.get(subnet_name=name)
mapping_objs = Mapping.objects.filter(subnet=name)
ip_start = subnet_info_obj.ip_range_start
ip_end = subnet_info_obj.ip_range_end
used_ip_list = []
for obj in mapping_objs: #Create list of used IPs
used_ip_list.append(obj.ip_or_cname)
index = 0
ip_range = list(netaddr.iter_iprange(ip_start, ip_end)) #Create the actual list of all IPs in the range
next_ip = str(ip_range[index])
while next_ip in used_ip_list:
index += 1
next_ip = str(ip_range[index])
return next_ip
开发者ID:rollerd,项目名称:django-dns,代码行数:25,代码来源:pylib.py
示例12: handler_ip_range
def handler_ip_range(string):
step = 1
if len(string.split(':')) > 1:
step = int(string.split(':')[-1])
ip_range = string.split(':')[0]
p_boundary = ip_range.split('-')
ip_begin = p_boundary[0]
ip_end = p_boundary[-1]
return map(lambda x: str(x), list(netaddr.iter_iprange(ip_begin, ip_end))[0::step])
开发者ID:yoobright,项目名称:vmt-scripts,代码行数:9,代码来源:ip_utils.py
示例13: get_ip_range
def get_ip_range(start, end):
generator = iter_iprange(start, end, step=1)
ips = []
while True:
try:
ips.append(str(generator.next()))
except StopIteration:
break
return ips
开发者ID:openstack,项目名称:steth,代码行数:9,代码来源:constants.py
示例14: expand_it
def expand_it(iplist):
results = []
for ip in iplist:
if type(ip) is list: #take care of range
[results.append(address) for address in iter_iprange(sorted(ip)[0], sorted(ip)[1])]
else: #expand cidr
for address in ip:
results.append(address)
return results
开发者ID:yoogz,项目名称:Pentesting-Scripts,代码行数:9,代码来源:easyscope.py
示例15: _setup_routes
def _setup_routes(self, if_dev, ver, ip_start, ip_end, gw_ip):
gw_ip_net = netaddr.IPNetwork(gw_ip)
if_dev.addr.add(ver, "%s/%s" % (ip_start, gw_ip_net.prefixlen), gw_ip_net.broadcast)
if_dev.route.add_gateway(str(gw_ip_net.ip))
if ip_start != ip_end:
local_nets = netaddr.cidr_merge(netaddr.iter_iprange(ip_start, ip_end))
max_pfx_len = ver == 4 and 32 or 128
for l in local_nets:
if l.prefixlen < max_pfx_len or str(l.ip) != ip_start:
if_dev.route._as_root("add", "local", str(l), "dev", if_dev.name, options=[ver])
开发者ID:kendriu,项目名称:python-opflex-agent,代码行数:10,代码来源:snat_iptables_manager.py
示例16: nova_add_range
def nova_add_range(self, start, end):
"""
Takes a start and end range, and creates individual host addresses.
:param start: A string containing the start of the range.
:param end: A string containing the end of the range.
"""
ip_list = list(netaddr.iter_iprange(start, end))
for ip in ip_list:
self.nova_add_floating(ip)
开发者ID:paulczar,项目名称:cookbook-openstack-compute,代码行数:10,代码来源:add_floaters.py
示例17: setUp
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
# Deploy guest vm
try:
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["server_without_disk"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.testdata["domainid"],
zoneid=self.testdata["zoneid"],
serviceofferingid=self.service_offering.id,
mode=self.testdata["mode"],
)
except Exception as e:
raise Exception(
"Warning: Exception during vm deployment: {}".format(e))
self.vm_response = VirtualMachine.list(
self.apiclient,
id=self.virtual_machine.id
)
self.assertEqual(
isinstance(self.vm_response, list),
True,
"Check VM list response returned a valid list"
)
self.ip_range = list(
netaddr.iter_iprange(
unicode(
self.testdata["vlan_ip_range"]["startip"]), unicode(
self.testdata["vlan_ip_range"]["endip"])))
self.nic_ip = netaddr.IPAddress(
unicode(
self.vm_response[0].nic[0].ipaddress))
self.debug("vm got {} as ip address".format(self.nic_ip))
self.assertIn(
self.nic_ip,
self.ip_range,
"VM did not get the ip address from the new ip range"
)
ip_alias = self.dbclient.execute(
"select ip4_address from nic_ip_alias;"
)
self.alias_ip = str(ip_alias[0][0])
self.debug("alias ip : %s" % self.alias_ip)
self.assertNotEqual(
self.alias_ip,
None,
"Error in creating ip alias. Please check MS logs"
)
self.cleanup.append(self.virtual_machine)
return
开发者ID:Tosta-Mixta,项目名称:cloudstack,代码行数:54,代码来源:test_multiple_ip_ranges.py
示例18: _create_lports
def _create_lports(self, lswitch, lport_create_args = [], lport_amount=1):
LOG.info("create %d lports on lswitch %s" % \
(lport_amount, lswitch["name"]))
self.RESOURCE_NAME_FORMAT = "lport_XXXXXX_XXXXXX"
batch = lport_create_args.get("batch", lport_amount)
LOG.info("Create lports method: %s" % self.install_method)
install_method = self.install_method
network_cidr = lswitch.get("cidr", None)
ip_addrs = None
if network_cidr:
end_ip = network_cidr.ip + lport_amount
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, network_cidr.last)
ovn_nbctl = self.controller_client("ovn-nbctl")
ovn_nbctl.set_sandbox("controller-sandbox", install_method)
ovn_nbctl.enable_batch_mode()
base_mac = [i[:2] for i in self.task["uuid"].split('-')]
base_mac[3:] = ['00']*3
flush_count = batch
lports = []
for i in range(lport_amount):
name = self.generate_random_name()
lport = ovn_nbctl.lport_add(lswitch["name"], name)
ip = str(ip_addrs.next()) if ip_addrs else ""
mac = utils.get_random_mac(base_mac)
ovn_nbctl.lport_set_addresses(name, [mac, ip])
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
开发者ID:jiajiadev,项目名称:ovn-scale-test,代码行数:52,代码来源:ovn.py
示例19: test_iprange_boundaries
def test_iprange_boundaries():
assert list(iter_iprange('192.0.2.0', '192.0.2.7')) == [
IPAddress('192.0.2.0'),
IPAddress('192.0.2.1'),
IPAddress('192.0.2.2'),
IPAddress('192.0.2.3'),
IPAddress('192.0.2.4'),
IPAddress('192.0.2.5'),
IPAddress('192.0.2.6'),
IPAddress('192.0.2.7'),
]
assert list(iter_iprange('::ffff:192.0.2.0', '::ffff:192.0.2.7')) == [
IPAddress('::ffff:192.0.2.0'),
IPAddress('::ffff:192.0.2.1'),
IPAddress('::ffff:192.0.2.2'),
IPAddress('::ffff:192.0.2.3'),
IPAddress('::ffff:192.0.2.4'),
IPAddress('::ffff:192.0.2.5'),
IPAddress('::ffff:192.0.2.6'),
IPAddress('::ffff:192.0.2.7'),
]
开发者ID:drkjam,项目名称:netaddr,代码行数:22,代码来源:test_ip_ranges.py
示例20: test_01_deploy_vm_in_new_cidr
def test_01_deploy_vm_in_new_cidr(self):
"""Deploy guest vm after adding guest IP range in new CIDR
1.Deploy guest vm
2.Verify vm gets the ip address from new cidr
"""
#Deploy guest vm
try :
self.virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["server_without_disk"],
templateid = self.template.id,
accountid = self.account.name,
domainid = self.services["domainid"],
zoneid = self.services["zoneid"],
serviceofferingid = self.service_offering.id,
mode = self.services["mode"],
)
except Exception as e :
raise Exception("Warning: Exception during vm deployment: {}".format(e))
self.vm_response = VirtualMachine.list(
self.apiclient,
id = self.virtual_machine.id
)
self.assertEqual(
isinstance(self.vm_response, list),
True,
"Check VM list response returned a valid list"
)
self.ip_range = list(netaddr.iter_iprange(unicode(self.services["vlan_ip_range"]["startip"]), unicode(self.services["vlan_ip_range"]["endip"])))
self.nic_ip = netaddr.IPAddress(unicode(self.vm_response[0].nic[0].ipaddress))
self.debug("vm got {} as ip address".format(self.nic_ip))
self.assertIn(
self.nic_ip,
self.ip_range,
"VM did not get the ip address from the new ip range"
)
self.virtual_machine.delete(self.apiclient)
expunge_del = Configurations.list(
self.apiclient,
name = 'expunge.delay'
)
expunge_int = Configurations.list(
self.apiclient,
name = 'expunge.interval'
)
wait_time = int(expunge_del[0].value) + int(expunge_int[0].value) + int(30)
self.debug("Waiting for {} seconds for the vm to expunge".format(wait_time))
#wait for the vm to expunge
time.sleep(wait_time)
return
开发者ID:itnihao,项目名称:cloudstack,代码行数:51,代码来源:test_multiple_ip_ranges.py
注:本文中的netaddr.iter_iprange函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论