本文整理汇总了Python中netaddr.IPNetwork方法的典型用法代码示例。如果您正苦于以下问题:Python netaddr.IPNetwork方法的具体用法?Python netaddr.IPNetwork怎么用?Python netaddr.IPNetwork使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netaddr
的用法示例。
在下文中一共展示了netaddr.IPNetwork方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_cf_domain
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def get_cf_domain(domain,cf_ranges):
if domain.endswith('cloudfront.net'):
return False
domain_ips = []
try:
domain_ips = socket.gethostbyname_ex(domain)[2]
except:
pass
for ip in domain_ips:
for ip_range in cf_ranges:
ip_network = IPNetwork(ip_range)
if ip in ip_network:
print(' [+] Found CloudFront domain --> ' + str(domain))
return True
return False
# test domains for CloudFront misconfigurations
示例2: ip_network_from_address
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def ip_network_from_address(address):
try:
ip_network = netaddr.IPNetwork(address)
except netaddr.AddrFormatError as e:
# address is not an IP address represented in an accepted string
# format.
e.message = ("invalid IP network: '%(address)s' (failed to detect a"
" valid IP network)") % {
'address': address}
raise
if ip_network.version == 4:
return ip_network
else:
raise NotSupported(
('invalid IP network: %(address)s (Internet Protocol version'
' %(version)s is not supported)') % {
'address': address,
'version': ip_network.version})
示例3: initialize
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def initialize(self):
self.fqdn = self.run("hostname")
self._read_machine_id()
# Find the node's IP address on the storage network
addrs = self.run("sudo ip -4 addr | awk '$1 == \"inet\" {print $2}'")
for addr in addrs.split("\n"):
ip_network = IPNetwork(addr)
if ip_network == Node.storage_network:
self.storage_ip = str(ip_network.ip)
break
if not getattr(self, "storage_ip", None):
msg = "Node at {} does not have an IP address on the storage" \
" network".format(self.address)
LOG.error(msg)
raise DashboardException(msg)
示例4: _is_valid_cidr
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def _is_valid_cidr(address):
"""Check if address is valid
The provided address can be a IPv6 or a IPv4
CIDR address.
"""
try:
# Validate the correct CIDR Address
netaddr.IPNetwork(address)
except netaddr.core.AddrFormatError:
return False
except UnboundLocalError:
# NOTE(MotoKen): work around bug in netaddr 0.7.5 (see detail in
# https://github.com/drkjam/netaddr/issues/2)
return False
# Prior validation partially verify /xx part
# Verify it here
ip_segment = address.split('/')
if (len(ip_segment) <= 1 or
ip_segment[1] == ''):
return False
return True
示例5: setIps
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def setIps(vm, node):
"""
Set the IPs of the VM from the info obtained from vSphere
"""
public_ips = []
private_ips = []
if node.guest:
for nic in node.guest.net:
if nic.ipAddress:
ip = nic.ipAddress
is_private = any([IPAddress(ip) in IPNetwork(mask) for mask in Config.PRIVATE_NET_MASKS])
if is_private:
private_ips.append(ip)
else:
public_ips.append(ip)
vm.setIps(public_ips, private_ips)
示例6: get_nets_common_cird
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def get_nets_common_cird(radl):
"""
Get a common CIDR in all the RADL nets
"""
nets = []
for num, net in enumerate(radl.networks):
provider_id = net.getValue('provider_id')
if net.getValue('create') == 'yes' and not net.isPublic() and not provider_id:
net_cidr = net.getValue('cidr')
if not net_cidr:
net_cidr = CloudConnector.DEFAULT_NET_CIDR
net_cidr_0 = IPNetwork(net_cidr.replace("*", "0"))
if net_cidr_0 not in nets:
nets.append(net_cidr_0)
net_cidr = IPNetwork(net_cidr.replace("*", str(num + 1)))
nets.append(net_cidr)
if len(nets) == 0: # there is no CIDR return the default one
return "10.0.0.0/16"
elif len(nets) == 1: # there is only one, return it
return nets[0]
else: # there are more, get the common CIDR
return str(spanning_cidr(nets))
示例7: get_ipv6_addr_by_EUI64
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def get_ipv6_addr_by_EUI64(cidr, mac):
"""Generate a IPv6 addr by EUI-64 with CIDR and MAC
:param str cidr: a IPv6 CIDR
:param str mac: a MAC address
:return: an IPv6 Address
:rtype: netaddr.IPAddress
"""
# Check if the prefix is IPv4 address
is_ipv4 = netaddr.valid_ipv4(cidr)
if is_ipv4:
msg = "Unable to generate IP address by EUI64 for IPv4 prefix"
raise TypeError(msg)
try:
eui64 = int(netaddr.EUI(mac).eui64())
prefix = netaddr.IPNetwork(cidr)
return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
except (ValueError, netaddr.AddrFormatError):
raise TypeError('Bad prefix or mac format for generating IPv6 '
'address by EUI-64: %(prefix)s, %(mac)s:'
% {'prefix': cidr, 'mac': mac})
except TypeError:
raise TypeError('Bad prefix type for generate IPv6 address by '
'EUI-64: %s' % cidr)
示例8: _add_routes
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def _add_routes(self, interface_name, routes=[]):
logger.info('adding custom route for interface: %s' % interface_name)
data = ""
for route in routes:
options = ""
if route.route_options:
options = " %s" % (route.route_options)
if route.default and not route.ip_netmask:
rt = netaddr.IPNetwork("0.0.0.0/0")
else:
rt = netaddr.IPNetwork(route.ip_netmask)
data += "up route add -net %s netmask %s gw %s%s\n" % (
str(rt.ip), str(rt.netmask), route.next_hop, options)
data += "down route del -net %s netmask %s gw %s%s\n" % (
str(rt.ip), str(rt.netmask), route.next_hop, options)
self.routes[interface_name] = data
logger.debug('route data: %s' % self.routes[interface_name])
示例9: get_cidr_name
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def get_cidr_name(cidr, ip_ranges_files, ip_ranges_name_key):
"""Read display name for CIDRs from ip-ranges files."""
for filename in ip_ranges_files:
ip_ranges = read_ip_ranges(filename, local_file=True)
for ip_range in ip_ranges:
ip_prefix = netaddr.IPNetwork(ip_range['ip_prefix'])
cidr = netaddr.IPNetwork(cidr)
if cidr in ip_prefix:
return ip_range[ip_ranges_name_key].strip()
for ip_range in aws_ip_ranges:
ip_prefix = netaddr.IPNetwork(ip_range['ip_prefix'])
cidr = netaddr.IPNetwork(cidr)
if cidr in ip_prefix:
return 'Unknown CIDR in %s %s' % (ip_range['service'], ip_range['region'])
return 'Unknown CIDR'
示例10: _build_IPv4
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def _build_IPv4(self, netblock, ipnetwork):
try:
n = netaddr.IPNetwork(ipnetwork)
if n.version != 4:
raise ValueError('invalid ip4 network: %d' % n.version)
except:
LOG.exception('%s - Invalid ip4 network: %s', self.name, ipnetwork)
return {}
item = {
'indicator': ipnetwork,
'type': 'IPv4',
'confidence': 100,
self.BLOCK_ATTRIBUTE: netblock,
'sources': [self.SOURCE_NAME]
}
return item
示例11: _build_IPv6
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def _build_IPv6(self, netblock, ipnetwork):
try:
n = netaddr.IPNetwork(ipnetwork)
if n.version != 6:
raise ValueError('invalid ip6 network: %d' % n.version)
except:
LOG.exception('%s - Invalid ip6 network: %s', self.name, ipnetwork)
return {}
item = {
'indicator': ipnetwork,
'type': 'IPv6',
'confidence': 100,
self.BLOCK_ATTRIBUTE: netblock,
'sources': [self.SOURCE_NAME]
}
return item
示例12: _range_from_indicator
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def _range_from_indicator(self, indicator):
if '-' in indicator:
start, end = map(
lambda x: int(netaddr.IPAddress(x)),
indicator.split('-', 1)
)
elif '/' in indicator:
ipnet = netaddr.IPNetwork(indicator)
start = int(ipnet.ip)
end = start+ipnet.size-1
else:
start = int(netaddr.IPAddress(indicator))
end = start
if (not (start >= 0 and start <= 0xFFFFFFFF)) or \
(not (end >= 0 and end <= 0xFFFFFFFF)):
LOG.error('%s - {%s} invalid IPv4 indicator',
self.name, indicator)
return None, None
return start, end
示例13: _build_IP
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def _build_IP(nodename, address_prefix, **keywords):
try:
ap = netaddr.IPNetwork(address_prefix)
except Exception:
LOG.exception('%s - Invalid ip range: %s', nodename, address_prefix)
return {}
if ap.version == 4:
type_ = 'IPv4'
elif ap.version == 6:
type_ = 'IPv6'
else:
LOG.error('{} - Unknown IP version: {}'.format(nodename, ap.version))
return {}
item = {
'indicator': address_prefix,
'type': type_,
'confidence': 100,
'sources': [nodename]
}
item.update(keywords)
return item
示例14: parse_ip_ranges
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def parse_ip_ranges(iprangesconfig):
ipranges = netaddr.IPSet([])
iprangessplit = [i.strip() for i in iprangesconfig.split(",")]
for iprange in iprangessplit:
if not iprange:
continue
try:
if "-" in iprange:
spl = iprange.split("-", 1)
ipns = netaddr.IPRange(spl[0], spl[1])
elif "*" in iprange:
ipns = netaddr.IPGlob(iprange)
else:
ipns = netaddr.IPNetwork(iprange)
ipranges.add(ipns)
except:
pprint("Bad IP definition: %s" % iprangesconfig)
sys.exit()
return ipranges
示例15: gen_ipv4_addr
# 需要导入模块: import netaddr [as 别名]
# 或者: from netaddr import IPNetwork [as 别名]
def gen_ipv4_addr(network_num="10.0.0.0", network_prefix="24", exclude_ips=[]):
"""
generate ipv4 address
:param network_num: network number to be used
:param network_prefix: prefix used to get subnet mask to calculate ip range
:param exclude_ips: the list of ipaddress should be excluded
:return: ipaddress of type str
"""
ip_regex = "^\d+.\d+.\d+.\d+$"
exclude_ips = set(exclude_ips)
if not re.match(ip_regex, network_num):
network_num = "10.0.0.0"
if not exclude_ips and network_prefix == "24":
exclude_ips.add(network_num)
exclude_ips.add('.'.join(network_num.split('.')[0:3]) + ".%s" %
str(1))
exclude_ips.add(('.'.join(network_num.split('.')[0:3]) + ".%s" %
str(255)))
network = netaddr.IPNetwork("%s/%s" % (network_num, network_prefix))
for ip_address in network:
if str(ip_address) not in exclude_ips:
yield str(ip_address)