Python netaddr.AddrFormatError() Examples

The following are 30 code examples for showing how to use netaddr.AddrFormatError(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module netaddr , or try the search function .

Example 1
Project: JetPack   Author: dsp-jetpack   File: discover_nodes.py    License: Apache License 2.0 6 votes vote down vote up
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 2
Project: JetPack   Author: dsp-jetpack   File: discover_nodes.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: tempest-lib   Author: openstack   File: data_utils.py    License: Apache License 2.0 6 votes vote down vote up
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 4
Project: datasploit   Author: dvopsway   File: datasploit.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: pythem   Author: m4n3dw0lf   File: arpoisoner.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 6
Project: pythem   Author: m4n3dw0lf   File: xploit.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: netmodules-plugin   Author: projectcalico   File: calico_mesos.py    License: Apache License 2.0 6 votes vote down vote up
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 8
Project: netman   Author: internap   File: arista.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: magnum   Author: openstack   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: ansible_f5   Author: mcgonagle   File: bigip_gtm_pool.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: ansible_f5   Author: mcgonagle   File: bigip_gtm_pool.py    License: Apache License 2.0 6 votes vote down vote up
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 12
Project: ansible_f5   Author: mcgonagle   File: bigip_selfip.py    License: Apache License 2.0 6 votes vote down vote up
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 13
Project: ansible_f5   Author: mcgonagle   File: bigip_selfip.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: tripleo-common   Author: openstack   File: baremetal.py    License: Apache License 2.0 6 votes vote down vote up
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 15
Project: JetPack   Author: dsp-jetpack   File: discover_nodes.py    License: Apache License 2.0 5 votes vote down vote up
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 16
Project: lsassy   Author: Hackndo   File: utils.py    License: MIT License 5 votes vote down vote up
def parse_targets(target):
    if '-' in target:
        ip_range = target.split('-')
        try:
            t = 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:
        return list(t)
    else:
        return [t.strip()] 
Example 17
Project: lanscan   Author: sumpfgottheit   File: lanscan.py    License: MIT License 5 votes vote down vote up
def scan(o, arg_network, vendor, portscan):
    networks = o['networks']  # type: Networks
    n = None  # type: Network
    if arg_network is None:
        n = networks.default_network
    else:
        try:
            i = int(arg_network)
            if 1 <= i <= len(networks.networks):
                n = networks.networks[i - 1]
            else:
                exit_n("No network for id {} found. Try 'lanscan networks' to get networks.".format(i))
        except ValueError:
            try:
                _n = netaddr.IPNetwork(arg_network)
                click.echo("Scan for: {}".format(_n.cidr))
                n = networks.get_network_for_netaddr_ip(_n)
            except (KeyError, netaddr.AddrFormatError) as e:
                exit_n(str(e))

    logger.debug("Network: {}".format(n.cidr))
    n.scan(vendor, portscan)
    header = ['ip', 'name', 'mac', 'alive', 'vendor', 'open ports']
    content = [(host.ip, host.hostname, host.mac, str(host.is_alive), host.vendor, ", ".join(map(str, host.open_port_numbers))) for host in
               n.neighbours]
    width, height = click.get_terminal_size()
    table = texttable.Texttable(max_width=width)
    table.set_deco(table.HEADER)
    table.header(header)
    table.add_rows(content, header=False)
    print(table.draw()) 
Example 18
Project: minemeld-core   Author: PaloAltoNetworks   File: feedredis.py    License: Apache License 2.0 5 votes vote down vote up
def _translate_ip_ranges(indicator, value=None):
    if value is not None and value['type'] != 'IPv4':
        return [indicator]

    try:
        ip_range = IPRange(*indicator.split('-', 1))

    except (AddrFormatError, ValueError, TypeError):
        return [indicator]

    return [str(x) if x.size != 1 else str(x.network) for x in ip_range.cidrs()] 
Example 19
Project: minemeld-core   Author: PaloAltoNetworks   File: visa.py    License: Apache License 2.0 5 votes vote down vote up
def _detect_ip_version(self, ip_addr):
        try:
            parsed = IPNetwork(ip_addr)
        except (AddrFormatError, ValueError):
            LOG.error('{} - Unknown IP version: {}'.format(self.name, ip_addr))
            return None

        if parsed.version == 4:
            return 'IPv4'

        if parsed.version == 6:
            return 'IPv6'

        return None 
Example 20
Project: minemeld-core   Author: PaloAltoNetworks   File: o365.py    License: Apache License 2.0 5 votes vote down vote up
def _analyze_item(self, item):
        result = []

        base_value = {}
        for wka in O365_API_FIELDS:
            if wka in item:
                base_value['o365_{}'.format(wka)] = item[wka]

        if self.disable_integrations and 'o365_notes' in base_value:
            if 'integration' in base_value['o365_notes'].lower():
                return result

        for url in item.get('urls', []):
            value = base_value.copy()
            value['type'] = 'URL'

            result.append([url, value])

        for ip in item.get('ips', []):
            try:
                parsed = netaddr.IPNetwork(ip)
            except (netaddr.AddrFormatError, ValueError):
                LOG.error('{} - Unknown IP version: {}'.format(self.name, ip))
                continue

            value = base_value.copy()
            if parsed.version == 4:
                value['type'] = 'IPv4'
            elif parsed.version == 6:
                value['type'] = 'IPv6'

            result.append([ip, value])

        return result 
Example 21
Project: minemeld-core   Author: PaloAltoNetworks   File: threatconnect.py    License: Apache License 2.0 5 votes vote down vote up
def _detect_ip_version(self, ip_addr):
        try:
            parsed = IPNetwork(ip_addr)
        except (AddrFormatError, ValueError):
            LOG.error('{} - Unknown IP version: {}'.format(self.name, ip_addr))
            return None

        if parsed.version == 4:
            return 'IPv4'

        if parsed.version == 6:
            return 'IPv6'

        return None 
Example 22
Project: dhcpcanon   Author: juga0   File: dhcpcapfsm.py    License: MIT License 5 votes vote down vote up
def process_received_ack(self, pkt):
        """Process a received ACK packet.

        Not specifiyed in [:rfc:`7844`].
        Probe the offered IP in [:rfc:`2131#section-2.2.`]::

            the allocating
            server SHOULD probe the reused address before allocating the
            address, e.g., with an ICMP echo request, and the client SHOULD
            probe the newly received address, e.g., with ARP.

            The client SHOULD broadcast an ARP
            reply to announce the client's new IP address and clear any
            outdated ARP cache entries in hosts on the client's subnet.

        It is also not specifiyed in [:rfc:`7844`] nor [:rfc:`2131`] how to
        check that the offered IP is valid.

        .. todo::
           - Check that nor ``dhclient`` nor ``systemd-networkd`` send an ARP.
           - Check how other implementations check that the ACK paremeters
             are valid, ie, if the ACK fields match the fields in the OFFER.
           - Check to which state the client should go back to when the
             offered parameters are not valid.

        """
        if isack(pkt):
            try:
                self.event = self.client.handle_ack(pkt,
                                                    self.time_sent_request)
            except AddrFormatError as err:
                logger.error(err)
                # NOTE: see previous TODO, maybe should go back to other state.
                raise self.SELECTING()
            # NOTE: see previous TODO, not checking address with ARP.
            logger.info('DHCPACK of %s from %s' %
                        (self.client.client_ip, self.client.server_ip))
            return True
        return False 
Example 23
Project: k8s-exec-plugin   Author: projectcalico   File: policy_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_parse_cidr_error(self):
        """Test invalid cidr policy statement"""
        assert_raises(AddrFormatError, self.parser.parse_line,
                      "allow from cidr 172.24.500.1") 
Example 24
Project: eclcli   Author: nttcom   File: validators.py    License: Apache License 2.0 5 votes vote down vote up
def validate_ip_subnet(parsed_args, attr_name):
    val = getattr(parsed_args, attr_name)
    if not val:
        return
    try:
        netaddr.IPNetwork(val)
    except (netaddr.AddrFormatError, ValueError):
        raise exceptions.CommandError(
            (_('%(attr_name)s "%(val)s" is not a valid CIDR.') %
             {'attr_name': attr_name.replace('_', '-'), 'val': val})) 
Example 25
Project: eclcli   Author: nttcom   File: validators.py    License: Apache License 2.0 5 votes vote down vote up
def validate_ip_subnet(parsed_args, attr_name):
    val = getattr(parsed_args, attr_name)
    if not val:
        return
    try:
        netaddr.IPNetwork(val)
    except (netaddr.AddrFormatError, ValueError):
        raise exceptions.CommandError(
            (_('%(attr_name)s "%(val)s" is not a valid CIDR.') %
             {'attr_name': attr_name.replace('_', '-'), 'val': val})) 
Example 26
Project: pythem   Author: m4n3dw0lf   File: scanner.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_range(self, targets):
        if targets is None:
            return None
        if targets is not 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 Exception as e:
                try:
                    target = socket.gethostbyname(self.targets)
                    target_list.append(target)
                    return target_list
                except:
                    print "[!] Exception caught: {}".format(e) 
Example 27
Project: pythem   Author: m4n3dw0lf   File: arpoisoner.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_range(self, targets):
        if targets is None:
            print "[!] IP address/range was not specified, will intercept only gateway requests and not replies."
            return None
        try:
            target_list = []
            for target in targets.split(','):
                if '/' in target:
                    self.range = True
                    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("[!] Select a valid IP address/range as target") 
Example 28
Project: piSociEty   Author: paranoidninja   File: ARP.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 29
Project: piSociEty   Author: paranoidninja   File: ARP.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 30
Project: netman   Author: internap   File: validators.py    License: Apache License 2.0 5 votes vote down vote up
def is_ip_network(data, **_):
    try:
        try:
            json_addr = json.loads(data)
            ip = IPNetwork("{}/{}".format(json_addr["address"], json_addr["mask"]))
        except ValueError:
            ip = IPNetwork(data)
    except (KeyError, AddrFormatError):
        raise BadRequest('Malformed content, should be : x.x.x.x/xx or {"address": "x.x.x.x", "mask": "xx"}')

    return {'validated_ip_network': ip}