本文整理汇总了Python中netaddr.valid_ipv6函数的典型用法代码示例。如果您正苦于以下问题:Python valid_ipv6函数的具体用法?Python valid_ipv6怎么用?Python valid_ipv6使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了valid_ipv6函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_from_tuple
def find_from_tuple(cls, link):
"""
Find link by providing a tuple with two ip addresses or two mac addresses
:param link: tuple with two string elements indicating source and destination (ip or mac addresses)
:returns: Link object
"""
try:
a = link[0]
b = link[1]
except IndexError:
raise ValueError('Expecting tuple with source and destination')
# find interfaces
if (valid_ipv4(a) and valid_ipv4(b)) or (valid_ipv6(a) and valid_ipv6(b)):
try:
a = Ip.objects.get(address=a).interface
b = Ip.objects.get(address=b).interface
except Ip.DoesNotExist as e:
raise LinkDataNotFound(e)
elif valid_mac(a) and valid_mac(b):
try:
a = Interface.objects.get(mac=a)
b = Interface.objects.get(mac=b)
except Interface.DoesNotExist as e:
raise LinkDataNotFound(e)
else:
raise ValueError('Expecting valid ipv4, ipv6 or mac address')
# find link with interfaces
# inverse order is also ok
q = Q(interface_a=a, interface_b=b) | Q(interface_a=b, interface_b=a)
link = Link.objects.filter(q).first()
if link is None:
raise LinkNotFound('Link matching query does not exist',
interface_a=a,
interface_b=b)
return link
示例2: validate_ip_addr
def validate_ip_addr(addr, version=None):
"""
Validates that an IP address is valid. Returns true if valid, false if
not. Version can be "4", "6", None for "IPv4", "IPv6", or "either"
respectively.
"""
if version == 4:
return netaddr.valid_ipv4(addr)
elif version == 6:
return netaddr.valid_ipv6(addr)
else:
return netaddr.valid_ipv4(addr) or netaddr.valid_ipv6(addr)
示例3: run
def run(args):
# minimal web server. serves files relative to the
# current directory.
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
filename=args['log-file'] ,level=logging.INFO)
port = args['port']
host = args['host']
os.chdir(args['cwd'])
Handler = ServerHandler
Handler.document_path = args['root-dir']
Handler.restrict_root_folder = (args['root-dir'] != args['cwd'])
if valid_ipv6(host):
server = HTTPServerV6
else:
server = HTTPServer
httpd = server((host, port), Handler)
scheme = 'http'
if args.has_key('cert-file') and args.has_key('key-file') and \
os.path.exists(args['cert-file']) and os.path.exists(args['key-file']):
scheme = 'https'
httpd.socket = ssl.wrap_socket (httpd.socket,
server_side=True,
certfile=args['cert-file'],
keyfile=args['key-file'])
logging.info("Starting simple http server at %s://%s:%s" % (scheme, host, port))
httpd.serve_forever()
示例4: _is_pingable
def _is_pingable(self, mgmt_ip="", count=5, timeout=1, interval='0.2',
**kwargs):
"""Checks whether an IP address is reachable by pinging.
Use linux utils to execute the ping (ICMP ECHO) command.
Sends 5 packets with an interval of 0.2 seconds and timeout of 1
seconds. Runtime error implies unreachability else IP is pingable.
:param ip: IP to check
:return: bool - True or string 'failure' depending on pingability.
"""
cmd_ping = 'ping'
if netaddr.valid_ipv6(mgmt_ip):
cmd_ping = 'ping6'
ping_cmd = [cmd_ping,
'-c', count,
'-W', timeout,
'-i', interval,
mgmt_ip]
try:
linux_utils.execute(ping_cmd, check_exit_code=True)
return True
except RuntimeError:
LOG.warning("Cannot ping ip address: %s", mgmt_ip)
return 'failure'
示例5: neighbor_add
def neighbor_add(self, address, remote_as,
enable_ipv4=DEFAULT_CAP_MBGP_IPV4,
enable_vpnv4=DEFAULT_CAP_MBGP_VPNV4,
enable_vpnv6=DEFAULT_CAP_MBGP_VPNV6,
next_hop=None, password=None, multi_exit_disc=None):
""" This method registers a new neighbor. The BGP speaker tries to
establish a bgp session with the peer (accepts a connection
from the peer and also tries to connect to it).
``address`` specifies the IP address of the peer. It must be
the string representation of an IP address. Only IP v4 is
supported now.
``remote_as`` specifies the AS number of the peer. It must be
an integer between 1 and 65535.
``enable_ipv4`` enables IPv4 address family for this
neighbor. The default is True.
``enable_vpnv4`` enables VPNv4 address family for this
neighbor. The default is False.
``enable_vpnv6`` enables VPNv6 address family for this
neighbor. The default is False.
``next_hop`` specifies the next hop IP address. If not
specified, host's ip address to access to a peer is used.
``password`` is used for the MD5 authentication if it's
specified. By default, the MD5 authenticaiton is disabled.
``multi_exit_disc`` specifies multi exit discriminator (MED) value.
The default is None and if not specified, MED value is
not sent to the neighbor. It must be an integer.
"""
bgp_neighbor = {}
bgp_neighbor[neighbors.IP_ADDRESS] = address
bgp_neighbor[neighbors.REMOTE_AS] = remote_as
bgp_neighbor[PEER_NEXT_HOP] = next_hop
bgp_neighbor[PASSWORD] = password
# v6 advertizement is available with only v6 peering
if netaddr.valid_ipv4(address):
bgp_neighbor[CAP_MBGP_IPV4] = enable_ipv4
bgp_neighbor[CAP_MBGP_IPV6] = False
bgp_neighbor[CAP_MBGP_VPNV4] = enable_vpnv4
bgp_neighbor[CAP_MBGP_VPNV6] = enable_vpnv6
elif netaddr.valid_ipv6(address):
bgp_neighbor[CAP_MBGP_IPV4] = False
bgp_neighbor[CAP_MBGP_IPV6] = True
bgp_neighbor[CAP_MBGP_VPNV4] = False
bgp_neighbor[CAP_MBGP_VPNV6] = False
else:
# FIXME: should raise an exception
pass
if multi_exit_disc:
bgp_neighbor[MULTI_EXIT_DISC] = multi_exit_disc
call('neighbor.create', **bgp_neighbor)
示例6: create_connection
def create_connection(address):
"""
Wrapper for socket.create_connection() function.
If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6
address, passes *address* to socket.create_connection().
If *host* is valid path to Unix Domain socket, tries to connect to
the server listening on the given socket.
:param address: IP address or path to Unix Domain socket.
:return: Socket instance.
"""
host, _port = address
if (netaddr.valid_ipv4(host)
or netaddr.valid_ipv6(host)):
return socket.create_connection(address)
elif os.path.exists(host):
sock = None
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(host)
except socket.error as e:
if sock is not None:
sock.close()
raise e
return sock
else:
raise ValueError('Invalid IP address or Unix Socket: %s' % host)
示例7: parse_server_string
def parse_server_string(server_str):
"""
Parses the given server_string and returns a list of host and port.
If it's not a combination of host part and port, the port element
is a null string. If the input is invalid expression, return a null
list.
"""
try:
# First of all, exclude pure IPv6 address (w/o port).
if netaddr.valid_ipv6(server_str):
return (server_str, '')
# Next, check if this is IPv6 address with a port number combination.
if server_str.find("]:") != -1:
(address, port) = server_str.replace('[', '', 1).split(']:')
return (address, port)
# Third, check if this is a combination of an address and a port
if server_str.find(':') == -1:
return (server_str, '')
# This must be a combination of an address and a port
(address, port) = server_str.split(':')
return (address, port)
except Exception:
LOG.error(_('Invalid server_string: %s'), server_str)
return ('', '')
示例8: prefix_del
def prefix_del(self, prefix, route_dist=None):
""" This method deletes a advertized prefix.
``prefix`` must be the string representation of an IP network
(e.g., 10.1.1.0/24).
``route_dist`` specifies a route distinguisher value. This
parameter is necessary for only VPNv4 and VPNv6 address
families.
"""
func_name = 'network.del'
networks = {}
networks[PREFIX] = prefix
if route_dist:
func_name = 'prefix.delete_local'
networks[ROUTE_DISTINGUISHER] = route_dist
ip, masklen = prefix.split('/')
if netaddr.valid_ipv6(ip):
networks[ROUTE_FAMILY] = vrfs.VRF_RF_IPV6
# normalize IPv6 address expression
networks[PREFIX] = \
str(netaddr.IPAddress(ip)) + '/' + masklen
else:
networks[ROUTE_FAMILY] = vrfs.VRF_RF_IPV4
call(func_name, **networks)
示例9: _process_networks
def _process_networks(osutils, network_details):
reboot_required = False
ipv4_ns, ipv6_ns = NetworkConfigPlugin._get_default_dns_nameservers(
network_details)
for net in network_details.networks:
ip_address, prefix_len = net.address_cidr.split("/")
gateway = None
default_gw_route = [
r for r in net.routes if
netaddr.IPNetwork(r.network_cidr).prefixlen == 0]
if default_gw_route:
gateway = default_gw_route[0].gateway
nameservers = net.dns_nameservers
if not nameservers:
if netaddr.valid_ipv6(ip_address):
nameservers = ipv6_ns
else:
nameservers = ipv4_ns
LOG.info(
"Setting static IP configuration on network adapter "
"\"%(name)s\". IP: %(ip)s, prefix length: %(prefix_len)s, "
"gateway: %(gateway)s, dns: %(dns)s",
{"name": net.link, "ip": ip_address, "prefix_len": prefix_len,
"gateway": gateway, "dns": nameservers})
reboot = osutils.set_static_network_config(
net.link, ip_address, prefix_len, gateway, nameservers)
reboot_required = reboot or reboot_required
return reboot_required
示例10: request
def request(self, url, method='GET', body=None, headers=None,
ssl_verify=True, stream=False):
_headers = {'Content-Type': 'application/json'}
_headers.update(headers or {})
parsed_url = urlparse.urlparse(url)
port = parsed_url.port
hostname = parsed_url.hostname
scheme = parsed_url.scheme
if netaddr.valid_ipv6(hostname):
hostname = "[%s]" % hostname
relative_url = parsed_url.path
if parsed_url.query:
relative_url = relative_url + "?" + parsed_url.query
LOG.info(_("Doing %(method)s on %(relative_url)s"),
{'method': method, 'relative_url': relative_url})
if body:
LOG.info(_("Body: %s") % body)
if port:
_url = "%s://%s:%d%s" % (scheme, hostname, int(port), relative_url)
else:
_url = "%s://%s%s" % (scheme, hostname, relative_url)
response = requests.request(method, _url, data=body, headers=_headers,
verify=ssl_verify, stream=stream)
return response
示例11: is_ip
def is_ip(self, ip_addr=None):
"""
Return true if valid IP address return false if invalid IP address
:param ip_addr: optional IP to pass. Takes from root class if not specified
>>> from ipinformation import IPInformation
>>> print IPInformation(ip_address='8.8.8.8').is_ip()
True
>>> print IPInformation(ip_address='NotAnIP').is_ip()
False
"""
if not ip_addr:
ip_addr = self.ip_address
valid = True
if netaddr.valid_ipv4(ip_addr): # IPv4 Address
if not re.match(valid_ip_regex, ip_addr):
valid = False
elif netaddr.valid_ipv6(ip_addr):
pass
else:
# print '"%s" is not a valid IP Address.' %ip_addr
valid = False
return valid
示例12: _handle_host_snat_ip
def _handle_host_snat_ip(self, host_snat_ips):
for hsi in host_snat_ips:
LOG.debug(_("Auto-allocated host SNAT IP: %s"), hsi)
es = hsi.get('external_segment_name')
if not es:
continue
nh = self.ext_seg_next_hop.setdefault(es, ExtSegNextHopInfo(es))
if nh.from_config:
continue # ignore auto-allocation if manually set
ip = hsi.get('host_snat_ip')
gw = ("%s/%s" % (hsi['gateway_ip'], hsi['prefixlen'])
if (hsi.get('gateway_ip') and hsi.get('prefixlen')) else None)
updated = False
if netaddr.valid_ipv4(ip):
if ip != nh.ip_start or gw != nh.ip_gateway:
nh.ip_start = ip
nh.ip_gateway = gw
updated = True
elif netaddr.valid_ipv6(ip):
if ip != nh.ip6_start or gw != nh.ip6_gateway:
nh.ip6_start = ip
nh.ip6_gateway = gw
updated = True
else:
LOG.info(_("Ignoring invalid auto-allocated SNAT IP %s"), ip)
if updated:
# Clear the interface so that SNAT iptables will be
# re-created as required; leave MAC as is so that it will
# be re-used
nh.next_hop_iface = None
LOG.info(_("Add/update SNAT info: %s"), nh)
示例13: _output_hosts_file
def _output_hosts_file(self):
"""Writes a dnsmasq compatible hosts file."""
r = re.compile('[:.]')
buf = six.StringIO()
for port in self.network.ports:
for alloc in port.fixed_ips:
name = 'host-%s.%s' % (r.sub('-', alloc.ip_address),
self.conf.dhcp_domain)
set_tag = ''
# (dzyu) Check if it is legal ipv6 address, if so, need wrap
# it with '[]' to let dnsmasq to distinguish MAC address from
# IPv6 address.
ip_address = alloc.ip_address
if netaddr.valid_ipv6(ip_address):
ip_address = '[%s]' % ip_address
if getattr(port, 'extra_dhcp_opts', False):
if self.version >= self.MINIMUM_VERSION:
set_tag = 'set:'
buf.write('%s,%s,%s,%s%s\n' %
(port.mac_address, name, ip_address,
set_tag, port.id))
else:
buf.write('%s,%s,%s\n' %
(port.mac_address, name, ip_address))
name = self.get_conf_file_name('host')
utils.replace_file(name, buf.getvalue())
return name
示例14: parse_server_string
def parse_server_string(server_str):
"""Parses the given server_string and returns a tuple of host and port.
If it's not a combination of host part and port, the port element
is an empty string. If the input is invalid expression, return a tuple of
two empty strings.
"""
try:
# First of all, exclude pure IPv6 address (w/o port).
if netaddr.valid_ipv6(server_str):
return (server_str, "")
# Next, check if this is IPv6 address with a port number combination.
if server_str.find("]:") != -1:
(address, port) = server_str.replace("[", "", 1).split("]:")
return (address, port)
# Third, check if this is a combination of an address and a port
if server_str.find(":") == -1:
return (server_str, "")
# This must be a combination of an address and a port
(address, port) = server_str.split(":")
return (address, port)
except (ValueError, netaddr.AddrFormatError):
LOG.error(_LE("Invalid server_string: %s"), server_str)
return ("", "")
示例15: is_connective
def is_connective(self, ping_timeout=20.0):
"""
Check if host network is connective via ping command
:param ping_timeout: time to wait for response
:type ping_timeout: float
:return: True if address is connective via ping command,
False otherwise
:rtype: bool
"""
host_address = self.host.ip
# Leave it for future support of IPV6
ping_cmd = "ping6" if netaddr.valid_ipv6(self.host.ip) else "ping"
self.logger.info(
"Check if address is connective via ping in given timeout %s",
ping_timeout
)
command = [
ping_cmd,
"-c", "1",
"-w", str(ping_timeout),
host_address
]
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out, _ = p.communicate()
if p.returncode:
self.logger.debug(
"Failed to ping address %s: %s", host_address, out
)
return False
return True