本文整理汇总了Python中netaddr.valid_ipv6函数的典型用法代码示例。如果您正苦于以下问题:Python valid_ipv6函数的具体用法?Python valid_ipv6怎么用?Python valid_ipv6使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了valid_ipv6函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:patrickprn,项目名称:nodeshot,代码行数:35,代码来源:link.py
示例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)
开发者ID:ContainerSolutions,项目名称:calico,代码行数:12,代码来源:common.py
示例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()
开发者ID:SlapOS,项目名称:slapos,代码行数:32,代码来源:simplehttpserver.py
示例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'
开发者ID:openstack,项目名称:tacker,代码行数:26,代码来源:ping.py
示例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)
开发者ID:girishprb,项目名称:ryu,代码行数:60,代码来源:bgpspeaker.py
示例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)
开发者ID:vinaykothiyal,项目名称:ryu,代码行数:29,代码来源:zclient.py
示例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 ('', '')
开发者ID:DinaBelova,项目名称:nova,代码行数:28,代码来源:utils.py
示例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)
开发者ID:rainmetersjtu,项目名称:ryu,代码行数:28,代码来源:bgpspeaker.py
示例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
开发者ID:openstack,项目名称:cloudbase-init,代码行数:33,代码来源:networkconfig.py
示例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
开发者ID:JamesBai,项目名称:cinder,代码行数:30,代码来源:client.py
示例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
开发者ID:neu5ron,项目名称:ipinformation,代码行数:27,代码来源:ipinformation.py
示例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)
开发者ID:AKamyshnikova,项目名称:python-opflex-agent,代码行数:31,代码来源:gbp_ovs_agent.py
示例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
开发者ID:vijayendrabvs,项目名称:ssl-neutron,代码行数:30,代码来源:dhcp.py
示例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 ("", "")
开发者ID:zhangtinglu,项目名称:nova,代码行数:27,代码来源:utils.py
示例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
开发者ID:cynepco3hahue,项目名称:python-rrmngmnt,代码行数:33,代码来源:network.py
示例16: _format_address_for_dnsmasq
def _format_address_for_dnsmasq(address):
# (dzyu) Check if it is legal ipv6 address, if so, need wrap
# it with '[]' to let dnsmasq to distinguish MAC address from
# IPv6 address.
if netaddr.valid_ipv6(address):
return '[%s]' % address
return address
开发者ID:glove747,项目名称:liberty-neutron,代码行数:7,代码来源:dhcp.py
示例17: _build_base_url
def _build_base_url(self, scheme):
proto_str = "%s://" % scheme
host_str = ("[%s]" % self._host if netaddr.valid_ipv6(self._host)
else self._host)
port_str = ":%d" % (self._api_ssl_port if scheme == "https"
else self._api_port)
return proto_str + host_str + port_str
开发者ID:openstack,项目名称:osprofiler,代码行数:7,代码来源:loginsight.py
示例18: take_action
def take_action(self, args):
configp = self.fetch_config(args)
instance_root = configp.get('slapos','instance_root')
master_url = urlparse(configp.get('slapos','master_url'))
master_hostname = master_url.hostname
# Check that we have IPv6 ready
if configp.has_option('slapformat', 'ipv6_interface'):
ipv6_interface = configp.get('slapformat', 'ipv6_interface')
else:
ipv6_interface = configp.get('slapformat', 'interface_name')
_waitIpv6Ready(ipv6_interface)
# Check that node can ping master
if valid_ipv4(master_hostname):
_test_ping(master_hostname)
elif valid_ipv6(master_hostname):
_test_ping6(master_hostname)
else:
# hostname
_ping_hostname(master_hostname)
app = SlapOSApp()
# Make sure slapos node format returns ok
while not _runFormat(app):
print("[BOOT] [ERROR] Fail to format, try again in 15 seconds...")
sleep(15)
# Make sure slapos node bang returns ok
while not _runBang(app):
print("[BOOT] [ERROR] Fail to bang, try again in 15 seconds...")
sleep(15)
_removeTimestamp(instance_root)
开发者ID:SlapOS,项目名称:slapos.core,代码行数:34,代码来源:boot.py
示例19: getAddress
def getAddress(self, allow_tap=False):
"""
Return a list of the interface address not attributed to any partition, (which
are therefore free for the computer itself).
Returns:
False if the interface isn't available, else the list of the free addresses.
"""
if self.interface is None:
return dict(addr=self.address, netmask=self.netmask)
computer_partition_address_list = []
for partition in self.partition_list:
for address in partition.address_list:
if netaddr.valid_ipv6(address['addr']):
computer_partition_address_list.append(address['addr'])
# Going through addresses of the computer's interface
for address_dict in self.interface.getGlobalScopeAddressList():
# Comparing with computer's partition addresses
if address_dict['addr'] not in computer_partition_address_list:
return address_dict
if allow_tap:
# all addresses on interface are for partition, so lets add new one
computer_tap = Tap('compdummy')
computer_tap.createWithOwner(User('root'), attach_to_tap=True)
self.interface.addTap(computer_tap)
return self.interface.addAddr()
# Can't find address
raise NoAddressOnInterface('No valid IPv6 found on %s.' %
self.interface.name)
开发者ID:pombredanne,项目名称:slapos.core,代码行数:32,代码来源:format.py
示例20: is_valid_ip_address
def is_valid_ip_address(ip_address, ip_version):
if int(ip_version) == 4:
return netaddr.valid_ipv4(ip_address)
elif int(ip_version) == 6:
return netaddr.valid_ipv6(ip_address)
else:
raise exception.ManilaException(
_("Provided improper IP version '%s'.") % ip_version)
开发者ID:aawm,项目名称:manila,代码行数:8,代码来源:utils.py
注:本文中的netaddr.valid_ipv6函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论