本文整理汇总了Python中netaddr.iter_iprange函数的典型用法代码示例。如果您正苦于以下问题:Python iter_iprange函数的具体用法?Python iter_iprange怎么用?Python iter_iprange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iter_iprange函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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")
示例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
示例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)
示例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)
示例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
示例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'),
]
示例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
示例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))
示例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
示例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])
示例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
示例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
示例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])