本文整理匯總了Python中ipaddress.ip_network方法的典型用法代碼示例。如果您正苦於以下問題:Python ipaddress.ip_network方法的具體用法?Python ipaddress.ip_network怎麽用?Python ipaddress.ip_network使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ipaddress
的用法示例。
在下文中一共展示了ipaddress.ip_network方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: run_validation
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def run_validation(self, site_design, orchestrator=None):
"""
Ensures that the network CIDR provided is acceptable to MAAS which
means the CIDR should not have host bits set
"""
network_list = site_design.networks or []
if not network_list:
msg = 'No networks found.'
self.report_warn(
msg, [],
'Site design likely incomplete without defined networks')
else:
for net in network_list:
# Verify that the CIDR does not have host bits set
try:
ipaddress.ip_network(net.cidr)
except ValueError as e:
if str(e) == (net.cidr + " has host bits set"):
msg = 'The provided CIDR %s has host bits set' % net.cidr
valid_cidr = ipaddress.ip_network(net.cidr, strict=False)
self.report_error(
msg, [net.doc_ref],
"Provide a CIDR acceptable by MAAS: %s" % str(valid_cidr))
return
示例2: ensure_subnet
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def ensure_subnet(vpc, availability_zone=None):
if availability_zone is not None and availability_zone not in availability_zones():
msg = "Unknown availability zone {} (choose from {})"
raise AegeaException(msg.format(availability_zone, list(availability_zones())))
for subnet in vpc.subnets.all():
if availability_zone is not None and subnet.availability_zone != availability_zone:
continue
break
else:
from ipaddress import ip_network
from ... import config
subnet_cidrs = ip_network(str(config.vpc.cidr[ARN.get_region()])).subnets(new_prefix=config.vpc.subnet_prefix)
subnets = {}
for az, subnet_cidr in zip(availability_zones(), subnet_cidrs):
logger.info("Creating subnet with CIDR %s in %s, %s", subnet_cidr, vpc, az)
subnets[az] = resources.ec2.create_subnet(VpcId=vpc.id, CidrBlock=str(subnet_cidr), AvailabilityZone=az)
clients.ec2.get_waiter("subnet_available").wait(SubnetIds=[subnets[az].id])
add_tags(subnets[az], Name=__name__)
clients.ec2.modify_subnet_attribute(SubnetId=subnets[az].id,
MapPublicIpOnLaunch=dict(Value=config.vpc.map_public_ip_on_launch))
subnet = subnets[availability_zone] if availability_zone is not None else list(subnets.values())[0]
return subnet
示例3: test_SubnetReservationSet
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def test_SubnetReservationSet():
resv = reservations.SubnetReservationSet()
assert len(resv) == 0
net = ipaddress.ip_network(u'10.0.0.0/8')
resv.add(net)
assert len(resv) == 1
assert net in resv
# Overlapping, __contains__ should return True.
netA = ipaddress.ip_network(u'10.10.10.0/24')
assert netA in resv
# Non-overlapping, __contains__ should return False.
netB = ipaddress.ip_network(u'192.168.0.0/16')
assert netB not in resv
示例4: is_payfast_ip_address
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def is_payfast_ip_address(ip_address_str):
"""
Return True if ip_address_str matches one of PayFast's server IP addresses.
Setting: `PAYFAST_IP_ADDRESSES`
:type ip_address_str: str
:rtype: bool
"""
# TODO: Django system check for validity?
payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
conf.DEFAULT_PAYFAST_IP_ADDRESSES)
if sys.version_info < (3,):
# Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
# (On Python 3, this should generally not happen:
# let unexpected bytes values fail as expected.)
ip_address_str = unicode(ip_address_str) # noqa: F821
payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses] # noqa: F821
return any(ip_address(ip_address_str) in ip_network(payfast_address)
for payfast_address in payfast_ip_addresses)
示例5: get_cidr
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def get_cidr(iplist):
cidrs = []
for ip in iplist:
cidr = re.sub(r'\d+$', '0/24', ip)
cidrs.append(ipaddress.ip_network(cidr))
result = []
for cidr in cidrs:
for i in iplist:
ip = ipaddress.ip_address(i)
if ip in cidr:
result.append(str(cidr))
break
out = get_top(result)
for i in out:
cidr, num = i.split('|')
print(cidr, num)
示例6: iscdn
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def iscdn(host):
result = True
# noinspection PyBroadException
try:
if not re.search(r'\d+\.\d+\.\d+\.\d+', host):
host = parse_ip(host)
for cdn in cdns:
if ipaddress.ip_address(host) in ipaddress.ip_network(cdn):
result = False
except Exception:
pass
# noinspection PyBroadException
try:
with geoip2.database.Reader('data/GeoLite2-ASN.mmdb') as reader:
response = reader.asn(host)
for i in ASNS:
if response.autonomous_system_number == int(i):
result = False
except Exception:
pass
return result
示例7: get_request_ip
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def get_request_ip(request: Any, context: Optional[Dict] = None) -> Optional[str]:
if request._cache.get('request_ip'):
return str(request._cache.get('request_ip', ''))
if request.transport:
if not context:
context = {}
real_ip_header = context.get('options', {}).get('http', {}).get('real_ip_header', 'X-Forwarded-For')
real_ip_from = context.get('options', {}).get('http', {}).get('real_ip_from', [])
if isinstance(real_ip_from, str):
real_ip_from = [real_ip_from]
peername = request.transport.get_extra_info('peername')
request_ip = None
if peername:
request_ip, _ = peername
if real_ip_header and real_ip_from and request.headers.get(real_ip_header) and request_ip and len(real_ip_from):
if any([ipaddress.ip_address(request_ip) in ipaddress.ip_network(cidr) for cidr in real_ip_from]):
request_ip = request.headers.get(real_ip_header).split(',')[0].strip().split(' ')[0].strip()
request._cache['request_ip'] = request_ip
return request_ip
return None
示例8: _match_whitelist
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def _match_whitelist(self, address: str, whitelist: str) -> bool:
trimmed_address = re.sub(r"/32$", "", address)
if address in whitelist:
raise PluginException(
cause=f"Address Object not created because the host {address} was found in the whitelist as {address}.",
assistance=f"If you would like to block this host, remove {address} from the whitelist and try again.")
elif '/' not in trimmed_address:
pass
for address_object in whitelist:
if self._determine_address_type(address_object) == "cidr":
net = ip_network(address_object, False)
ip = ip_address(trimmed_address)
if ip in net:
raise PluginException(
cause=f"Address Object not created because the host {address}"
f" was found in the whitelist as {address_object}.",
assistance="If you would like to block this host,"
f" remove {address_object} from the whitelist and try again.")
return False
示例9: find_internal_ip_on_device_network
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str:
"""
For a given UPnP device, return the internal IP address of this host machine that can
be used for a NAT mapping.
"""
parsed_url = urlparse(upnp_dev.location)
# Get an ipaddress.IPv4Network instance for the upnp device's network.
upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False)
for iface in netifaces.interfaces():
for family, addresses in netifaces.ifaddresses(iface).items():
# TODO: Support IPv6 addresses as well.
if family != netifaces.AF_INET:
continue
for item in addresses:
if ipaddress.ip_address(item["addr"]) in upnp_dev_net:
return item["addr"]
raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname)
示例10: __init__
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def __init__(self, match_type, ignore_case, value, tags):
assert match_type in [ _tag_mapping.MATCH_TYPE_DEFAULT,
_tag_mapping.MATCH_TYPE_GLOB,
_tag_mapping.MATCH_TYPE_REGEX,
_tag_mapping.MATCH_TYPE_SUBDOMAIN,
_tag_mapping.MATCH_TYPE_CIDR ]
assert isinstance(ignore_case, bool)
assert value is not None
assert isinstance(tags, list)
assert all([isinstance(t, str) for t in tags])
self.match_type = match_type
self.ignore_case = ignore_case
self.value = value
self.tags = tags
# if we have a regex go ahead and compile it
if self.match_type == _tag_mapping.MATCH_TYPE_REGEX:
self.compiled_regex = re.compile(self.value, flags=re.I if ignore_case else 0)
# if we have a cidr go ahead and create the object used to match it
if self.match_type == _tag_mapping.MATCH_TYPE_CIDR:
self.compiled_cidr = ipaddress.ip_network(value)
示例11: test_get_prefixes_for_ix_network
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def test_get_prefixes_for_ix_network(self, *_):
api = PeeringDB()
ix_network_id = 29146
with patch(
"peeringdb.http.requests.get", return_value=MockedResponse(status_code=404)
):
# Must be empty
self.assertFalse(api.get_prefixes_for_ix_network(0))
known_prefixes = [
ipaddress.ip_network("2001:db8:1337::/64"),
ipaddress.ip_network("203.0.113.0/24"),
]
found_prefixes = []
for ix_prefix in api.get_prefixes_for_ix_network(ix_network_id):
self.assertIn(ix_prefix, known_prefixes)
示例12: has_potential_ix_peering_sessions
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def has_potential_ix_peering_sessions(self, internet_exchange=None):
"""
Returns True if there are potential `InternetExchangePeeringSession` for this
`AutonomousSystem`. If the `internet_exchange` parameter is given, it will
only check for potential sessions in the given `InternetExchange`.
"""
if not self.potential_internet_exchange_peering_sessions:
return False
if not internet_exchange:
return len(self.potential_internet_exchange_peering_sessions) > 0
for session in self.potential_internet_exchange_peering_sessions:
for prefix in internet_exchange.get_prefixes():
if session in ipaddress.ip_network(prefix):
return True
return False
示例13: insert_network
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def insert_network(self, prefix, data_offset, strict = True):
self.entries_count += 1
ipnet = ipaddress.ip_network(prefix, strict=False)
if ipnet.version == 6 and self.ip_version != 6:
raise Exception('Encoder: insert_network: cannot add IPv6 address in IPv4 table')
if ipnet.version == 4 and self.ip_version == 6:
base4in6 = ipaddress.IPv6Address(u'::ffff:0:0')
v4in6addr = ipaddress.IPv6Address(int(ipnet.network_address)+int(base4in6))
# Maxmind DBs skips the first 96 bits (do not include the 0xffff)
if self.compat:
v4in6addr = ipaddress.IPv6Address(int(ipnet.network_address))
v4in6addr_plen = ipnet.prefixlen + 96
ipnet = ipaddress.IPv6Network(u'{}/{}'.format(str(v4in6addr), v4in6addr_plen), strict=False)
#print(ipnet)
self.add_to_trie(ipnet, data_offset, strict=strict)
示例14: parse_targets
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def parse_targets(target):
try:
if '-' in target:
start_ip, end_ip = target.split('-')
try:
end_ip = ip_address(end_ip)
except ValueError:
first_three_octets = start_ip.split(".")[:-1]
first_three_octets.append(end_ip)
end_ip = ip_address(
".".join(first_three_octets)
)
for ip_range in summarize_address_range(ip_address(start_ip), end_ip):
for ip in ip_range:
yield str(ip)
else:
for ip in ip_network(target, strict=False):
yield str(ip)
except ValueError:
yield str(target)
示例15: _validate_args
# 需要導入模塊: import ipaddress [as 別名]
# 或者: from ipaddress import ip_network [as 別名]
def _validate_args(subnet, region, colo):
if '/' not in subnet:
raise BadParam('Invalid subnet.', msg_ch=u'請使用cidr格式的網段')
_is_valide_region(region)
if colo not in SubnetIpDal.get_colo_by_group('subnet'):
raise BadParam('Invalid colo', msg_ch=u'請先配置機房')
try:
sub = ipaddress.ip_network(subnet)
except Exception as e:
raise BadParam('Invalid subnet: %s' % e, msg_ch=u'錯誤的網段格式')
prefix = sub.prefixlen
if sub.version == 4:
if prefix < 16 or prefix > 32:
raise BadParam('Invalid subnet.', msg_ch=u'IPv4掩碼長度在[16-32]之間')
else:
if prefix < 64 or prefix > 128:
raise BadParam('Invalid subnet.', msg_ch=u'IPv6掩碼長度在[64-128]之間')