Python netaddr.AddrFormatError() Examples
The following are 30
code examples of netaddr.AddrFormatError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
netaddr
, or try the search function
.
Example #1
Source File: bigip_selfip.py From ansible_f5 with Apache License 2.0 | 6 votes |
def address(self, value): pattern = '^(?P<ip>[0-9A-Fa-f:.]+)%?(?P<rd>\d+)?\/(?P<nm>\d+)$' matches = re.match(pattern, value) if not matches: raise F5ModuleError( "The specified address is malformed. Please see documentation." ) try: ip = matches.group('ip') self._values['ip'] = str(IPAddress(ip)) except AddrFormatError: raise F5ModuleError( 'The provided address is not a valid IP address' ) self._values['route_domain'] = matches.group('rd') self._values['netmask'] = matches.group('nm')
Example #2
Source File: data_utils.py From tempest-lib with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: discover_nodes.py From JetPack with Apache License 2.0 | 6 votes |
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})
Example #4
Source File: discover_nodes.py From JetPack with Apache License 2.0 | 6 votes |
def ip_address_from_address(address): try: ip_address = netaddr.IPAddress(address) except ValueError as e: # address contains a CIDR prefix, netmask, or hostmask. e.message = ('invalid IP address: %(address)s (detected CIDR, netmask,' ' hostmask, or subnet)') % {'address': address} raise except netaddr.AddrFormatError as e: # address is not an IP address represented in an accepted string # format. e.message = ("invalid IP address: '%(address)s' (failed to detect a" " valid IP address)") % {'address': address} raise if ip_address.version == 4: return ip_address else: raise NotSupported( ('invalid IP address: %(address)s (Internet Protocol version' ' %(version)s is not supported)') % { 'address': address, 'version': ip_address.version})
Example #5
Source File: baremetal.py From tripleo-common with Apache License 2.0 | 6 votes |
def run(self, context): existing = self._existing_ips() try: ip_addresses = self._ip_address_list() except netaddr.AddrFormatError as exc: LOG.error("Cannot parse network address: %s", exc) return actions.Result( error="%s: %s" % (type(exc).__name__, str(exc)) ) result = [] # NOTE(dtantsur): we iterate over IP addresses last to avoid # spamming the same BMC with too many requests in a row. for username, password in self.credentials: for port in self.ports: port = int(port) for ip in ip_addresses: if (ip, port) in existing or (ip, None) in existing: LOG.info('Skipping existing node %s:%s', ip, port) continue result.append({'ip': ip, 'username': username, 'password': password, 'port': port}) return result
Example #6
Source File: datasploit.py From datasploit with GNU General Public License v3.0 | 6 votes |
def auto_select_target(target, output=None): """Auto selection logic""" print "Target: %s" % target try: inp=IPAddress(target); if inp.is_private() or inp.is_loopback(): print "Internal IP Detected : Skipping" sys.exit() else: print "Looks like an IP, running ipOsint...\n" ipOsint.run(target, output) except SystemExit: print "exiting" except AddrFormatError: if re.match('[^@]+@[^@]+\.[^@]+', target): print "Looks like an EMAIL, running emailOsint...\n" emailOsint.run(target, output) elif get_tld(target, fix_protocol=True,fail_silently=True) is not None: print "Looks like a DOMAIN, running domainOsint...\n" domainOsint.run(target, output) else: print "Nothing Matched assuming username, running usernameOsint...\n" usernameOsint.run(target, output) except: print "Unknown Error Occured"
Example #7
Source File: arpoisoner.py From pythem with GNU General Public License v3.0 | 6 votes |
def __init__(self, gateway, targets, interface, myip, mymac): try: self.gateway = str(IPAddress(gateway)) except AddrFormatError as e: print "[-] Select a valid IP address as gateway" iptables() set_ip_forwarding(1) self.gateway_mac = None self.range = False self.targets = self.get_range(targets) self.send = True self.interval = 3 self.interface = interface self.myip = myip self.mymac = mymac self.socket = conf.L3socket(iface=self.interface) self.socket2 = conf.L2socket(iface=self.interface)
Example #8
Source File: arista.py From netman with Apache License 2.0 | 6 votes |
def _apply_interface_vlan_data(self, vlans): config = self._fetch_interface_vlans_config(vlans) for interface in split_on_dedent(config): if regex.match("^.*Vlan(\d+)$", interface[0]): vlan = _find_vlan_by_number(vlans, regex[0]) for line in interface[1:]: if regex.match(" *ip helper-address (.*)", line): try: vlan.dhcp_relay_servers.append(IPAddress(regex[0])) except AddrFormatError: self.logger.warning( 'Unsupported IP Helper address found in Vlan {} : {}'.format(vlan.number, regex[0])) if regex.match(" *ip virtual-router address (.*)", line): vlan.varp_ips.append(IPNetwork(regex[0])) if regex.match(" *load-interval (.*)", line): vlan.load_interval = int(regex[0]) if regex.match(" *no mpls ip", line): vlan.mpls_ip = False
Example #9
Source File: utils.py From magnum with Apache License 2.0 | 6 votes |
def validate_dns(dns_list): """Validate a string is a single dns address or comma separated dns list :param dns_list: dns_list to be validated :returns: original dns_list. :raise: InvalidDNS if dns format is invalid """ dns_nameservers = dns_list.split(',') try: for dns in dns_nameservers: netaddr.IPAddress(dns.strip(), version=4, flags=netaddr.INET_PTON) except netaddr.AddrFormatError: raise exception.InvalidDNS(dns=dns_list) else: return dns_list
Example #10
Source File: bigip_gtm_pool.py From ansible_f5 with Apache License 2.0 | 6 votes |
def fallback_ip(self): if self._values['fallback_ip'] is None: return None if self._values['fallback_ip'] == 'any': return 'any' try: address = IPAddress(self._values['fallback_ip']) if address.version == 4: return str(address.ip) elif address.version == 6: return str(address.ip) return None except AddrFormatError: raise F5ModuleError( 'The provided fallback address is not a valid IPv4 address' )
Example #11
Source File: xploit.py From pythem with GNU General Public License v3.0 | 6 votes |
def tcppwn(self, payload): try: self.target = str(IPAddress(self.target)) except AddrFormatError as e: try: self.target = gethostbyname(self.target) except Exception as e: print "[-] Select a valid IP address or domain name as target." print "[!] Exception caught: {}".format(e) return try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.settimeout(4) self.socket.connect((self.target, self.port)) self.socket.send(payload) while True: self.socket.recv(1024) except KeyboardInterrupt: return except Exception as e: if 'Connection refused' in e: print "[-] Connection refused." return
Example #12
Source File: bigip_gtm_pool.py From ansible_f5 with Apache License 2.0 | 6 votes |
def fallback_ip(self): if self._values['fallback_ip'] is None: return None if self._values['fallback_ip'] == 'any': return 'any' if self._values['fallback_ip'] == 'any6': return 'any6' try: address = IPAddress(self._values['fallback_ip']) if address.version == 4: return str(address.ip) elif address.version == 6: return str(address.ip) return None except AddrFormatError: raise F5ModuleError( 'The provided fallback address is not a valid IPv4 address' )
Example #13
Source File: bigip_selfip.py From ansible_f5 with Apache License 2.0 | 6 votes |
def route_domain(self): if self.want.route_domain is None: return None try: address = IPNetwork(self.have.ip) if self.want.netmask is not None: nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.want.netmask) cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.want.netmask) elif self.have.netmask is not None: nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.have.netmask) cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.have.netmask) if nipnet != cipnet: return nipnet except AddrFormatError: raise F5ModuleError( 'The provided address/netmask value was invalid' )
Example #14
Source File: calico_mesos.py From netmodules-plugin with Apache License 2.0 | 6 votes |
def _validate_ip_addrs(ip_addrs, ip_version=None): if not isinstance(ip_addrs, list): raise IsolatorException( "IP addresses must be provided as JSON list, not: %s" % type(ip_addrs)) validated_ip_addrs = [] for ip_addr in ip_addrs: try: ip = IPAddress(ip_addr) except AddrFormatError: raise IsolatorException("IP address could not be parsed: %s" % ip_addr) if ip_version and ip.version != ip_version: raise IsolatorException("IPv%d address must not be placed in IPv%d" " address field." % (ip.version, ip_version)) else: validated_ip_addrs.append(ip) return validated_ip_addrs
Example #15
Source File: config.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def normalise_address(address): """Normalise an IP address into a form suitable for the `ntp` daemon. It seems to prefer non-mapped IPv4 addresses, for example. Hostnames are passed through. """ try: address = IPAddress(address) except AddrFormatError: return address # Hostname. else: if address.is_ipv4_mapped(): return address.ipv4() else: return address
Example #16
Source File: api_common.py From tacker with Apache License 2.0 | 5 votes |
def convert_exception_to_http_exc(e, faults, language): serializer = wsgi.JSONDictSerializer() e = translate(e, language) body = serializer.serialize( {'TackerError': get_exception_data(e)}) kwargs = {'body': body, 'content_type': 'application/json'} if isinstance(e, exc.HTTPException): # already an HTTP error, just update with content type and body e.body = body e.content_type = kwargs['content_type'] return e if isinstance(e, (exceptions.TackerException, netaddr.AddrFormatError, oslo_policy.PolicyNotAuthorized)): for fault in faults: if isinstance(e, fault): mapped_exc = faults[fault] break else: mapped_exc = exc.HTTPInternalServerError return mapped_exc(**kwargs) if isinstance(e, NotImplementedError): # NOTE(armando-migliaccio): from a client standpoint # it makes sense to receive these errors, because # extensions may or may not be implemented by # the underlying plugin. So if something goes south, # because a plugin does not implement a feature, # returning 500 is definitely confusing. kwargs['body'] = serializer.serialize( {'NotImplementedError': get_exception_data(e)}) return exc.HTTPNotImplemented(**kwargs) # NOTE(jkoelker) Everything else is 500 # Do not expose details of 500 error to clients. msg = _('Request Failed: internal server error while ' 'processing your request.') msg = translate(msg, language) kwargs['body'] = serializer.serialize( {'TackerError': get_exception_data(exc.HTTPInternalServerError(msg))}) return exc.HTTPInternalServerError(**kwargs)
Example #17
Source File: middleware.py From django-restricted-sessions with BSD 3-Clause "New" or "Revised" License | 5 votes |
def validate_ip(self, request, remote_ip): # When we aren't configured to restrict on IP address if not getattr(settings, 'RESTRICTEDSESSIONS_RESTRICT_IP', True): return True # When the IP address key hasn't yet been set on the request session if SESSION_IP_KEY not in request.session: return True # When there is no remote IP, check if one has been set on the session session_ip = request.session[SESSION_IP_KEY] if not remote_ip: if session_ip: # session has remote IP value so validate :-( return False else: # Session doesn't have remote IP value so possibly :-) return True # Compute fuzzy IP compare based on settings on compare sensitivity session_network = IPNetwork(session_ip) remote_ip = IPAddress(remote_ip) try: session_network = session_network.ipv4() remote_ip = remote_ip.ipv4() session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV4_LENGTH', 32) except AddrConversionError: try: session_network.prefixlen = getattr(settings, 'RESTRICTEDSESSIONS_IPV6_LENGTH', 64) except AddrFormatError: # session_network must be IPv4, but remote_ip is IPv6 return False return remote_ip in session_network
Example #18
Source File: ip_parser.py From MS17-010-Python with MIT License | 5 votes |
def parse_targets(target): if '-' in target: ip_range = target.split('-') try: hosts = IPRange(ip_range[0], ip_range[1]) except AddrFormatError: try: start_ip = IPAddress(ip_range[0]) start_ip_words = list(start_ip.words) start_ip_words[-1] = ip_range[1] start_ip_words = [str(v) for v in start_ip_words] end_ip = IPAddress('.'.join(start_ip_words)) t = IPRange(start_ip, end_ip) except AddrFormatError: t = target else: try: t = IPNetwork(target) except AddrFormatError: t = target if type(t) == IPNetwork or type(t) == IPRange: t = [str(ip) for ip in list(t)] return t else: return [str(t.strip())]
Example #19
Source File: undercloud_preflight.py From python-tripleoclient with Apache License 2.0 | 5 votes |
def _validate_in_cidr(subnet_props, subnet_name): cidr = netaddr.IPNetwork(subnet_props.cidr) def validate_addr_in_cidr(addr, pretty_name=None, require_ip=True, log_only=False): try: if netaddr.IPAddress(addr) not in cidr: message = (_('Config option {0} "{1}" not in defined ' 'CIDR "{2}"').format(pretty_name, addr, cidr)) if log_only: LOG.warning(message) else: LOG.error(message) raise FailedValidation(message) except netaddr.core.AddrFormatError: if require_ip: message = (_('Invalid IP address: %s') % addr) LOG.error(message) raise FailedValidation(message) validate_addr_in_cidr(subnet_props.gateway, 'gateway') # NOTE(hjensas): Ignore the default dhcp_start and dhcp_end if cidr is not # the default as well. I.e allow not specifying dhcp_start and dhcp_end. if not (subnet_props.cidr != constants.CTLPLANE_CIDR_DEFAULT and subnet_props.dhcp_start == constants.CTLPLANE_DHCP_START_DEFAULT and subnet_props.dhcp_end == constants.CTLPLANE_DHCP_END_DEFAULT): for start in subnet_props.dhcp_start: validate_addr_in_cidr(start, 'dhcp_start') for end in subnet_props.dhcp_end: validate_addr_in_cidr(end, 'dhcp_end') if subnet_name == CONF.local_subnet: validate_addr_in_cidr(str(netaddr.IPNetwork(CONF.local_ip).ip), 'local_ip') if (CONF.undercloud_service_certificate or CONF.generate_service_certificate): validate_addr_in_cidr(CONF['undercloud_public_host'], 'undercloud_public_host', require_ip=False, log_only=True) validate_addr_in_cidr(CONF['undercloud_admin_host'], 'undercloud_admin_host', require_ip=False)
Example #20
Source File: undercloud_preflight.py From python-tripleoclient with Apache License 2.0 | 5 votes |
def _validate_value_formats(): """Validate format of some values Certain values have a specific format that must be maintained in order to work properly. For example, local_ip must be in CIDR form, and the hostname must be a FQDN. """ try: local_ip = netaddr.IPNetwork(CONF.local_ip) if local_ip.prefixlen == 32: LOG.error(_('Invalid netmask')) raise netaddr.AddrFormatError(_('Invalid netmask')) # If IPv6 the ctlplane network uses the EUI-64 address format, # which requires the prefix to be /64 if local_ip.version == 6 and local_ip.prefixlen != 64: LOG.error(_('Prefix must be 64 for IPv6')) raise netaddr.AddrFormatError(_('Prefix must be 64 for IPv6')) except netaddr.core.AddrFormatError as e: message = (_('local_ip "{0}" not valid: "{1}" ' 'Value must be in CIDR format.') .format(CONF.local_ip, str(e))) LOG.error(message) raise FailedValidation(message) hostname = CONF['undercloud_hostname'] if hostname is not None and '.' not in hostname: message = (_('Hostname "%s" is not fully qualified.') % hostname) LOG.error(message) raise FailedValidation(message)
Example #21
Source File: undercloud_preflight.py From python-tripleoclient with Apache License 2.0 | 5 votes |
def _validate_ips(): def is_ip(value, param_name): try: netaddr.IPAddress(value) except netaddr.core.AddrFormatError: msg = (_('{0} "{1}" must be a valid IP address') .format(param_name, value)) LOG.error(msg) raise FailedValidation(msg) for ip in CONF.undercloud_nameservers: is_ip(ip, 'undercloud_nameservers')
Example #22
Source File: utilities.py From power-up with Apache License 2.0 | 5 votes |
def is_netmask(mask): from netaddr import AddrFormatError try: if IPAddress(mask).is_netmask(): res = True else: res = False except AddrFormatError: res = False return res
Example #23
Source File: discover_nodes.py From JetPack with Apache License 2.0 | 5 votes |
def ip_set_from_address_range(start, end): try: start_ip_address = ip_address_from_address(start) end_ip_address = ip_address_from_address(end) except (NotSupported, ValueError) as e: raise ValueError( ('invalid IP range: %(start)s-%(end)s (%(message)s)') % { 'start': start, 'end': end, 'message': e.message}) except netaddr.AddrFormatError as e: raise ValueError( ("invalid IP range: '%(start)s-%(end)s' (%(message)s)") % { 'start': start, 'end': end, 'message': e.message}) if start_ip_address > end_ip_address: raise ValueError( ('invalid IP range: %(start)s-%(end)s (lower bound IP greater than' ' upper bound)') % { 'start': start, 'end': end}) ip_range = netaddr.IPRange(start_ip_address, end_ip_address) return netaddr.IPSet(ip_range)
Example #24
Source File: arpspoof.py From polymorph with GNU General Public License v2.0 | 5 votes |
def get_range(self, targets): if targets is None: return None try: target_list = [] for target in targets.split(','): if '/' in target: target_list.extend(list(IPNetwork(target))) elif '-' in target: start_addr = IPAddress(target.split('-')[0]) try: end_addr = IPAddress(target.split('-')[1]) ip_range = IPRange(start_addr, end_addr) except AddrFormatError: end_addr = list(start_addr.words) end_addr[-1] = target.split('-')[1] end_addr = IPAddress('.'.join(map(str, end_addr))) ip_range = IPRange(start_addr, end_addr) target_list.extend(list(ip_range)) else: target_list.append(IPAddress(target)) return target_list except AddrFormatError: sys.exit("Specified an invalid IP address/range/network as target")
Example #25
Source File: arpspoof.py From polymorph with GNU General Public License v2.0 | 5 votes |
def __init__(self, options): try: self.gatewayip = str(IPAddress(options.gateway)) except AddrFormatError as e: sys.exit("Specified an invalid IP address as gateway") self.gatewaymac = options.gatewaymac if options.gatewaymac is None: self.gatewaymac = getmacbyip(options.gateway) if not self.gatewaymac: sys.exit("Error: could not resolve Gateway's mac address") self.ignore = self.get_range(options.ignore) if self.ignore is None: self.ignore = [] self.targets = self.get_range(options.targets) self.arpmode = options.arpmode self.debug = False self.send = True self.interval = 3 self.interface = options.interface self.myip = options.ip self.mymac = options.mac self.arp_cache = {} #log.debug("gatewayip => {}".format(self.gatewayip)) #log.debug("gatewaymac => {}".format(self.gatewaymac)) #log.debug("targets => {}".format(self.targets)) #log.debug("ignore => {}".format(self.ignore)) #log.debug("ip => {}".format(self.myip)) #log.debug("mac => {}".format(self.mymac)) #log.debug("interface => {}".format(self.interface)) #log.debug("arpmode => {}".format(self.arpmode)) #log.debug("interval => {}".format(self.interval))
Example #26
Source File: __init__.py From quay with Apache License 2.0 | 5 votes |
def resolve_ip(self, ip_address): """ Attempts to return resolved information about the specified IP Address. If such an attempt fails, returns None. """ if not ip_address: return None try: parsed_ip = IPAddress(ip_address) except AddrFormatError: return ResolvedLocation("invalid_ip", None, self.sync_token, None) # Try geoip classification try: geoinfo = self.geoip_db.country(ip_address) except geoip2.errors.AddressNotFoundError: geoinfo = None if self.amazon_ranges is None or parsed_ip not in self.amazon_ranges: if geoinfo: return ResolvedLocation( "internet", geoinfo.country.iso_code, self.sync_token, geoinfo.country.iso_code, ) return ResolvedLocation("internet", None, self.sync_token, None) return ResolvedLocation( "aws", None, self.sync_token, geoinfo.country.iso_code if geoinfo else None )
Example #27
Source File: bigip_snat_pool.py From ansible_f5 with Apache License 2.0 | 5 votes |
def _format_member_address(self, member): try: address = str(IPAddress(member)) address = '/{0}/{1}'.format(self.partition, address) return address except (AddrFormatError, ValueError): raise F5ModuleError( 'The provided member address is not a valid IP address' )
Example #28
Source File: bigip_device_connectivity.py From ansible_f5 with Apache License 2.0 | 5 votes |
def _get_validated_ip_address(self, address): try: IPAddress(self._values[address]) return self._values[address] except AddrFormatError: raise F5ModuleError( "The specified '{0}' is not a valid IP address".format( address ) )
Example #29
Source File: bigip_device_connectivity.py From ansible_f5 with Apache License 2.0 | 5 votes |
def _validate_unicast_failover_address(self, address): try: result = IPAddress(address) return str(result) except KeyError: raise F5ModuleError( "An 'address' must be supplied when configuring unicast failover" ) except AddrFormatError: raise F5ModuleError( "'address' field in unicast failover is not a valid IP address" )
Example #30
Source File: fields.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def _clean_addr(self, addr): try: addr = IPAddress(addr) except AddrFormatError as error: message = str(error) # netaddr has good messages. message = message[:1].upper() + message[1:] + "." raise ValidationError(message) else: return str(addr)