本文整理汇总了Python中ipaddr.IPNetwork方法的典型用法代码示例。如果您正苦于以下问题:Python ipaddr.IPNetwork方法的具体用法?Python ipaddr.IPNetwork怎么用?Python ipaddr.IPNetwork使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ipaddr
的用法示例。
在下文中一共展示了ipaddr.IPNetwork方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen_nets
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def gen_nets(self, locations, infile):
for row in csv.DictReader(infile):
location = locations.get(row['geoname_id'])
if location is None:
continue
nets = [ipaddr.IPNetwork(row['network'])]
country_iso_code = location['country_iso_code'] or location['continent_code']
fips_code = geoname2fips.get(location['geoname_id'])
if fips_code is None:
logging.debug('Missing fips-10-4 for {}'.format(location['subdivision_1_name']))
fips_code = '00'
else:
logging.debug('fips-10-4 for {} is {}'.format(location['subdivision_1_name'], fips_code))
yield nets, (country_iso_code,
serialize_text(fips_code), # region
serialize_text(decode_text(location['city_name'])),
serialize_text(row['postal_code']),
row['latitude'],
row['longitude'],
location['metro_code'],
'') # area_code
示例2: check_cidr
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def check_cidr(self, environment, network):
"""
check if network is a subnet of the father environment
:param environment: environment id
:param network: environment cidr
:return: boolean
"""
if environment.father_environment:
id_env_father = environment.father_environment.id
else:
return True
cidr_env_father = self.get(env_id=id_env_father)
for cidr in cidr_env_father:
if ipaddr.IPNetwork(network).overlaps(ipaddr.IPNetwork(cidr.network)):
return True
return False
示例3: nextAvailableCIDR
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def nextAvailableCIDR(self, subnets, network):
"""
Try to aloccate
:param subnets:
:param network:
:return:
"""
if not subnets:
subnet = list(NETADDR(network.network).subnet(int(network.subnet_mask)))[0]
return str(subnet)
subnet = NETADDR(subnets.latest('id').network).next()
if ipaddr.IPNetwork(subnet).overlaps(ipaddr.IPNetwork(network.network)):
return str(subnet)
return self.searchNextAvailableCIDR(subnets)
示例4: main
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def main():
if len(sys.argv) != 2:
print 'Usage: python webscan.py 192.168.1.1/24'
else:
time_start = time.time()
threads = []
thread_count = 200 #线程数
queue = Queue.Queue()
cidrip = sys.argv[1] #接收输入IP段
ips = ipaddr.IPNetwork(cidrip)
for ip in ips:
queue.put(ip)
for i in xrange(thread_count):
threads.append(PortScan(queue))
for t in threads:
t.start()
for t in threads:
t.join()
print 'ALL Finished, Running Time:' + str(time.time() - time_start)
示例5: Validate
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def Validate(self, value, unused_key=None):
"""Validates a subnet."""
if value is None:
raise validation.MissingAttribute('subnet must be specified')
if not isinstance(value, basestring):
raise validation.ValidationError('subnet must be a string, not \'%r\'' %
type(value))
try:
ipaddr.IPNetwork(value)
except ValueError:
raise validation.ValidationError('%s is not a valid IPv4 or IPv6 subnet' %
value)
parts = value.split('/')
if len(parts) == 2 and not re.match('^[0-9]+$', parts[1]):
raise validation.ValidationError('Prefix length of subnet %s must be an '
'integer (quad-dotted masks are not '
'supported)' % value)
return value
示例6: __init__
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def __init__(self, vid, conf=None):
if conf is None:
conf = {}
self.vid = vid
self.tagged = []
self.untagged = []
self.name = conf.setdefault('name', str(vid))
self.description = conf.setdefault('description', self.name)
self.controller_ips = conf.setdefault('controller_ips', [])
if self.controller_ips:
self.controller_ips = [
ipaddr.IPNetwork(ip) for ip in self.controller_ips]
self.unicast_flood = conf.setdefault('unicast_flood', True)
self.routes = conf.setdefault('routes', {})
self.ipv4_routes = {}
self.ipv6_routes = {}
if self.routes:
self.routes = [route['route'] for route in self.routes]
for route in self.routes:
ip_gw = ipaddr.IPAddress(route['ip_gw'])
ip_dst = ipaddr.IPNetwork(route['ip_dst'])
assert(ip_gw.version == ip_dst.version)
if ip_gw.version == 4:
self.ipv4_routes[ip_dst] = ip_gw
else:
self.ipv6_routes[ip_dst] = ip_gw
self.arp_cache = {}
self.nd_cache = {}
self.max_hosts = conf.setdefault('max_hosts', None)
self.host_cache = {}
示例7: merge_ranges
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def merge_ranges(ranges):
range_data = [[ipaddr.IPNetwork(r).numhosts, ipaddr.IPNetwork(r)] for r in ranges]
ranges = [r[1] for r in sorted(range_data)[::-1]]
unique_ranges = [str(r) for r in sort_ranges(ranges)]
return unique_ranges
示例8: checkFirewall
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def checkFirewall(clientip):
try: clientinrange = any([IPAddress(clientip) in IPNetwork(i) for i in AceConfig.firewallnetranges])
except: logger.error('Check firewall netranges settings !'); return False
return not ((AceConfig.firewallblacklistmode and clientinrange) or (not AceConfig.firewallblacklistmode and not clientinrange))
示例9: classifySearchString
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def classifySearchString(data):
data = data.strip()
asn = None
try:
asn = int(data)
except ValueError:
pass
if asn:
if asn < 1:
raise ValueError('Invalid as number (negative or zero)')
return ASNumber(asn)
if data.upper().startswith('AS-'):
return ASMacro(data.upper()) # as macros are always uppcase
if data.upper().startswith('AS'):
try:
return ASNumber(int(data[2:]))
except ValueError:
return ASMacro(data)
try:
ipaddr.IPNetwork(data)
return Prefix(data)
except ValueError:
pass
raise ValueError('Cannot classify %s' % data)
示例10: check_prefix
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def check_prefix(self, network_address, subnet_mask):
"""
check if subnet mask is correct, based on network mask.
:param network_address: environment cidr
:param subnet_mask: environment cidr subnet mask
:return: boolean
"""
network = ipaddr.IPNetwork(network_address)
return True if int(network.prefixlen) <= int(subnet_mask) else False
示例11: searchNextAvailableCIDR
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def searchNextAvailableCIDR(self, subnets):
"""
Method that search next availacle cidr.
:param subnets: all subnets of environment.
:return: available subnet
"""
log.debug("searchNextAvailableCIDR")
for idx, _ in enumerate(subnets):
if int(subnets[idx].network_last_ip) + 1 is not int(subnets[idx+1].network_first_ip):
subnet = subnets[idx].network
new_subnet = NETADDR(subnet).next()
if not ipaddr.IPNetwork(new_subnet).overlaps(ipaddr.IPNetwork(subnets[idx+1].network)):
return str(new_subnet)
return ""
示例12: post
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def post(self, env_cidr):
try:
if env_cidr.get('id'):
self.id = env_cidr.get('id')
self.network = env_cidr.get('network')
self.network_first_ip = env_cidr.get('network_first_ip')
self.network_last_ip = env_cidr.get('network_last_ip')
self.network_mask = env_cidr.get('network_mask')
self.ip_version = env_cidr.get('ip_version')
self.subnet_mask = env_cidr.get('subnet_mask')
if not self.check_prefix(self.network, self.subnet_mask):
raise CIDRErrorV3("The prefix %s is not valid for the network %s" % (self.subnet_mask, self.network))
objects = EnvCIDR.objects.filter(id_env=int(env_cidr.get('environment')))
for obj in objects:
if ipaddr.IPNetwork(obj.network).overlaps(ipaddr.IPNetwork(self.network)):
raise CIDRErrorV3("%s overlaps %s" % (self.network, obj.network))
environment = Ambiente().get_by_pk(int(env_cidr.get('environment')))
self.id_env = environment
self.id_network_type = TipoRede().get_by_pk(int(env_cidr.get('network_type')))
self.save()
except Exception as e:
raise CIDRErrorV3(e)
return self.id
示例13: _ValidateEntry
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def _ValidateEntry(self, entry):
if not entry.subnet:
return MISSING_SUBNET
try:
ipaddr.IPNetwork(entry.subnet)
except ValueError:
return BAD_IPV_SUBNET % entry.subnet
parts = entry.subnet.split('/')
if len(parts) == 2 and not re.match('^[0-9]+$', parts[1]):
return BAD_PREFIX_LENGTH % entry.subnet
示例14: main
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def main():
print ''
logo_encode = 'ICAgIF9fXyAgICBfX19fX19fX18gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgLyAgIHwgIC8gLyAvIF9fXy9fX19fX19fX19fX19fX18gIF9fX18gIF9fXyAgX19fX18KICAvIC98IHwgLyAvIC9cX18gXC8gX19fLyBfXyAgLyBfXyBcLyBfXyBcLyBfIFwvIF9fXy8KIC8gX19fIHwvIC8gL19fXy8gLyAvX18vIC9fLyAvIC8gLyAvIC8gLyAvICBfXy8gLyAgICAKL18vICB8Xy9fL18vL19fX18vXF9fXy9cX19fXy9fLyAvXy9fLyAvXy9cX19fL18v='
logo = base64.b64decode(logo_encode)
print logo + '\n\n'
print 'github:https://github.com/aedoo/' + '\n\n'
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='cidr_ip', help='IP segment like 192.168.1.1/16 contains 65536 IP.')
parser.add_argument('-t', dest='thread_number', type=int, default=100, help='Setting the number of threads')
args = parser.parse_args()
print ''
IP_Duan = str(args.cidr_ip)
try:
IPs = ipaddr.IPNetwork(IP_Duan)
thread_number = args.thread_number
threads = []
queue = Queue.Queue()
for ip in IPs:
queue.put(str(ip))
for i in xrange(thread_number):
threads.append(AllScanner(queue))
for t in threads:
t.start()
for t in threads:
t.join()
except Exception:
parser.print_help()
示例15: load_cluster_networks
# 需要导入模块: import ipaddr [as 别名]
# 或者: from ipaddr import IPNetwork [as 别名]
def load_cluster_networks(self):
self.cluster_net = None
self.public_net = None
osd = self.get_alive_osd()
if osd is not None:
cluster_net_str = osd.config.get('cluster_network')
if cluster_net_str is not None and cluster_net_str != "":
self.cluster_net = IPNetwork(cluster_net_str)
public_net_str = osd.config.get('public_network', None)
if public_net_str is not None and public_net_str != "":
self.public_net = IPNetwork(public_net_str)