def _attach_vm_network_to_host_static_config(prefix, api, host_num):
    engine = api.system_service()

    host = test_utils.hosts_in_cluster_v4(engine, CLUSTER_NAME)[host_num]
    host_service = engine.hosts_service().host_service(id=host.id)

    nic_name = _host_vm_nics(prefix, host.name,
                             LIBVIRT_NETWORK_FOR_MANAGEMENT)[0]  # eth0
    ip_configuration = network_utils_v4.create_static_ip_configuration(
        VM_NETWORK_IPv4_ADDR.format(host_num+1),
        VM_NETWORK_IPv4_MASK,
        VM_NETWORK_IPv6_ADDR.format(host_num+1),
        VM_NETWORK_IPv6_MASK)

    network_utils_v4.attach_network_to_host(
        host_service,
        nic_name,
        VM_NETWORK,
        ip_configuration)

    host_nic = next(nic for nic in host_service.nics_service().list() if
                    nic.name == '{}.{}'.format(nic_name, VM_NETWORK_VLAN_ID))
    nt.assert_equals(IPAddress(host_nic.ip.address),
                     IPAddress(VM_NETWORK_IPv4_ADDR.format(host_num+1)))
    nt.assert_equals(IPAddress(host_nic.ipv6.address),
                     IPAddress(VM_NETWORK_IPv6_ADDR.format(host_num+1)))
Exemplo n.º 2
0
def main():
    opts, args = parseCommandLine()
    if len(args) == 1:
        dstAddr = IPAddress(args[0])
        srcAddr = None
    elif len(args) == 2:
        srcAddr = IPAddress(args[0])
        dstAddr = IPAddress(args[1])

    dstIfInfos = getIfaceInfo(dstAddr)
    if len(dstIfInfos) > 1:
        raise BaseException('Found more than one matching interface: %s' %
                            dstIfInfos)
    if srcAddr is None:
        srcAddr = IPAddress(dstIfInfos[0].ip)
    if srcAddr == dstAddr:
        raise BaseException(
            'Source address %s is equal to destination address %s' %
            (srcAddr, dstAddr))

    # http://osdir.com/ml/security.scapy.general/2007-11/msg00019.html
    conf.iface = dstIfInfos[0].name

    bind_layers(UDP, BVLC, sport=BACNET_PORT)
    bind_layers(UDP, BVLC, dport=BACNET_PORT)

    udp = IP(src=str(srcAddr), dst=str(dstAddr)) / UDP(sport=BACNET_PORT,
                                                       dport=BACNET_PORT)
    bvlc = udp / BVLC(function=BvlcFunction.REGISTER_FD, time_to_live=opts.ttl)
    bvlc.show2()
    send(bvlc)
Exemplo n.º 3
0
def _iter_merged_ranges(sorted_ranges):
    """Iterate over sorted_ranges, merging where possible

    Sorted ranges must be a sorted iterable of (version, first, last) tuples.
    Merging occurs for pairs like [(4, 10, 42), (4, 43, 100)] which is merged
    into (4, 10, 100), and leads to return value
    ( IPAddress(10, 4), IPAddress(100, 4) ), which is suitable input for the
    iprange_to_cidrs function.
    """
    if not sorted_ranges:
        return

    current_version, current_start, current_stop = sorted_ranges[0]

    for next_version, next_start, next_stop in sorted_ranges[1:]:
        if next_start == current_stop + 1 and next_version == current_version:
            # Can be merged.
            current_stop = next_stop
            continue
        # Cannot be merged.
        yield (IPAddress(current_start, current_version),
               IPAddress(current_stop, current_version))
        current_start = next_start
        current_stop = next_stop
        current_version = next_version
    yield (IPAddress(current_start,
                     current_version), IPAddress(current_stop,
                                                 current_version))
Exemplo n.º 4
0
def glob_to_iptuple(ipglob):
    """
    A function that accepts a glob-style IP range and returns the component
    lower and upper bound IP address.

    :param ipglob: an IP address range in a glob-style format.

    :return: a tuple contain lower and upper bound IP objects.
    """
    if not valid_glob(ipglob):
        raise AddrFormatError('not a recognised IP glob range: %r!' % ipglob)

    start_tokens = []
    end_tokens = []

    for octet in ipglob.split('.'):
        if '-' in octet:
            tokens = octet.split('-')
            start_tokens.append(tokens[0])
            end_tokens.append(tokens[1])
        elif octet == '*':
            start_tokens.append('0')
            end_tokens.append('255')
        else:
            start_tokens.append(octet)
            end_tokens.append(octet)

    return IPAddress('.'.join(start_tokens)), IPAddress('.'.join(end_tokens))
Exemplo n.º 5
0
 def find_in_routingTable(self, dstIp):
     ruta_sel = IPNetwork('0.0.0.0/0')
     for ruta in self.tablaEnrutamiento:
         if IPAddress(ruta[0]) == (IPAddress(dstIp) & IPAddress(ruta[1])):
             if int(ruta_sel.prefixlen) < int(IPAddress(ruta[1])):
                 ruta_sel = ruta
                 print "ruta sel: ", ruta_sel
     if ruta_sel[3] == None:
         return (dstIp, ruta_sel[2])
     else:
         return (ruta[ruta_sel[3]], ruta_sel[2])
Exemplo n.º 6
0
def apply_interface_running_config_data(vlan, data):
    for line in data:
        if regex.match("^ ip address ([^\s]*) ([^\s]*)(.*)", line):
            ip = IPNetwork("{}/{}".format(regex[0], regex[1]))
            if "secondary" not in regex[2]:
                vlan.ips.insert(0, ip)
            else:
                vlan.ips.append(ip)

        elif regex.match("^ ip access-group ([^\s]*) ([^\s]*).*", line):
            if regex[1] == "in":
                vlan.access_groups[IN] = regex[0]
            else:
                vlan.access_groups[OUT] = regex[0]

        elif regex.match("^ ip vrf forwarding ([^\s]*).*", line):
            vlan.vrf_forwarding = regex[0]

        elif regex.match("^ standby ([\d]+) (.*)", line):
            vrrp_group = next(
                (group
                 for group in vlan.vrrp_groups if str(group.id) == regex[0]),
                None)
            if vrrp_group is None:
                vrrp_group = VrrpGroup(id=int(regex[0]))
                vlan.vrrp_groups.append(vrrp_group)

            vrrp_info = regex[1].strip()

            if regex.match("^ip ([^\s]*).*", vrrp_info):
                vrrp_group.ips.append(IPAddress(regex[0]))
            elif regex.match("^timers ([^\s]*) ([^\s]*)", vrrp_info):
                vrrp_group.hello_interval = int(regex[0])
                vrrp_group.dead_interval = int(regex[1])
            elif regex.match("^priority ([^\s]*)", vrrp_info):
                vrrp_group.priority = int(regex[0])
            elif regex.match("^track ([^\s]*) decrement ([^\s]*)", vrrp_info):
                vrrp_group.track_id = regex[0]
                vrrp_group.track_decrement = int(regex[1])

        elif regex.match("^ ip helper-address ([^\s]*)", line):
            vlan.dhcp_relay_servers.append(IPAddress(regex[0]))

        elif regex.match("^ no ip proxy-arp", line):
            vlan.arp_routing = False

        elif regex.match("^ no ip redirects", line):
            vlan.icmp_redirects = False

        elif regex.match("^ ip verify unicast source reachable-via rx", line):
            vlan.unicast_rpf_mode = STRICT

        elif regex.match("^ ntp disable", line):
            vlan.ntp = False
Exemplo n.º 7
0
 def find_in_routingTable (self, dstIp):
     ruta_sel = [IPNetwork('0.0.0.0/0'),0,None]
     for ruta in self.tablaEnrutamiento:
         if IPAddress(ruta[0]) == (IPAddress(dstIp) & IPAddress(ruta[1])):
             if int(ruta_sel[0].prefixlen) < int(IPAddress(ruta[1])):
                 ruta_sel[0] = IPNetwork(ruta[0],ruta[1])    #Network
                 ruta_sel[1] = ruta[2]                       #Puerto
                 ruta_sel[2] = ruta[3]                       #Gateway
                 # print "ruta sel: ", ruta_sel
     if ruta_sel[2] == None:
         return (dstIp, ruta_sel[1])
     else:
         return (ruta[ruta_sel[2]], ruta_sel[1])
Exemplo n.º 8
0
 def randomipv6(cls, subnet='2001::', prefix=64):
     random.seed()
     ipv6_address = IPAddress(subnet) + random.getrandbits(16)
     ipv6_network = IPNetwork(ipv6_address)
     ipv6_network.prefixlen = prefix
     output = '{},{}'.format(ipv6_address, ipv6_network)
     return '{}'.format(ipv6_address), '{}'.format(ipv6_network)
Exemplo n.º 9
0
 def _is_ip(self, a, name):
     try:
         if a.get(name):
             IPAddress(a.get(name))
         return True
     except Exception:
         return False
Exemplo n.º 10
0
    def _load_zones(self):
        zonefile = cfg.CONF.ml2_snabb.zone_definition_file
        networks = {}
        if zonefile != '':
            zonelines = jsonutils.load(open(zonefile))
            for entry in zonelines:
                host, port, zone, vlan, subnet = entry["host"], entry[
                    "port"], entry["zone"], entry["vlan"], entry["subnet"]
                used = []
                for u in entry["used"]:
                    used.append(IPAddress(u))
                host = host.strip()
                port = port.strip()
                zone = int(zone)
                vlan = int(vlan)
                subnet = netaddr.IPNetwork(subnet)
                networks.setdefault(host, {})
                networks[host].setdefault(port, {})
                networks[host][port][zone] = (subnet, vlan, used)
                LOG.debug(
                    "Loaded zone host:%s port:%s "
                    "zone:%s subnet:%s vlan:%s", host, port, zone, subnet,
                    vlan)

        return networks
Exemplo n.º 11
0
def sendWhoIs(src, dst, count=1):
    '''
    @param dst: Destination IP or network 
    @todo: Use matching interface IP as src
    '''

    bindLayers()

    try:
        ipDst = IPNetwork(dst)
        dst = str(ipDst.broadcast)
    except:
        ipDst = IPAddress(dst)

    udp = IP(src=src, dst=dst) / UDP(sport=BACNET_PORT, dport=BACNET_PORT)
    bvlcBase = getBvlcBase(ipDst)
    bvlc = udp / BVLC(**bvlcBase)
    npduBase = getNpduBase(withApdu=True)
    npdu = bvlc / NPDU(**npduBase)
    apdu = npdu / APDU(pdu_type=PduType.UNCONFIRMED_REQUEST,
                       service_choice=UnconfirmedServiceChoice.WHO_IS)

    # sendp(): no packets on the wire?!
    # srloop(): How to match answer to request?
    send(apdu, count=count)
Exemplo n.º 12
0
    def ipv6_link_local(self):
        """
        .. note:: This poses security risks in certain scenarios. \
            Please read RFC 4941 for details. Reference: RFCs 4291 and 4941.

        :return: new link local IPv6 `IPAddress` object based on this `EUI` \
            using the technique described in RFC 4291.
        """
        int_val = 0xfe800000000000000000000000000000

        if self.version == 48:
            eui64_tokens = ["%02x" % i for i in self[0:3]] + ['ff', 'fe'] + \
                ["%02x" % i for i in self[3:6]]
            int_val += int(''.join(eui64_tokens), 16)
        else:
            int_val += self._value

        # Modified EUI-64 format interface identifiers are formed by inverting
        # the "u" bit (universal/local bit in IEEE EUI-64 terminology) when
        # forming the interface identifier from IEEE EUI-64 identifiers.  In
        # the resulting Modified EUI-64 format, the "u" bit is set to one (1)
        # to indicate universal scope, and it is set to zero (0) to indicate
        # local scope.
        int_val ^= 0x00000000000000000200000000000000

        return IPAddress(int_val, 6)
Exemplo n.º 13
0
    def update(self, iterable, flags=0):
        """
        Update the contents of this IP set with the union of itself and
        other IP set.

        :param iterable: an iterable containing IP addresses and subnets.

        :param flags: decides which rules are applied to the interpretation
            of the addr value. See the netaddr.core namespace documentation
            for supported constant values.

        """
        if isinstance(iterable, IPSet):
            self._cidrs = dict.fromkeys((ip for ip in cidr_merge(
                _dict_keys(self._cidrs) + _dict_keys(iterable._cidrs))), True)
            return
        elif isinstance(iterable, (IPNetwork, IPRange)):
            self.add(iterable)
            return

        if not hasattr(iterable, '__iter__'):
            raise TypeError('an iterable was expected!')
        #   An iterable containing IP addresses or subnets.
        mergeable = []
        for addr in iterable:
            if isinstance(addr, _int_type):
                addr = IPAddress(addr, flags=flags)
            mergeable.append(addr)

        for cidr in cidr_merge(_dict_keys(self._cidrs) + mergeable):
            self._cidrs[cidr] = True

        self.compact()
Exemplo n.º 14
0
def iter_nmap_range(iprange):
    """
    The nmap security tool supports a custom type of IPv4 range using multiple
    hyphenated octets. This generator provides iterators yielding IP addresses
    according to this rule set.

    @param iprange: an nmap-style IP address range.

    @return: an iterator producing IPAddress objects for each IP in the range.
    """
    if not valid_nmap_range(iprange):
        raise AddrFormatError('invalid nmap range: %s' % iprange)

    matrix = []
    tokens = iprange.split('.')

    for token in tokens:
        if '-' in token:
            octets = token.split('-', 1)
            pair = (int(octets[0]), int(octets[1]))
        else:
            pair = (int(token), int(token))
        matrix.append(pair)

    for w in range(matrix[0][0], matrix[0][1] + 1):
        for x in range(matrix[1][0], matrix[1][1] + 1):
            for y in range(matrix[2][0], matrix[2][1] + 1):
                for z in range(matrix[3][0], matrix[3][1] + 1):
                    yield IPAddress("%d.%d.%d.%d" % (w, x, y, z))
Exemplo n.º 15
0
    def add(self, addr, flags=0):
        """
        Adds an IP address or subnet or IPRange to this IP set. Has no effect if
        it is already present.

        Note that where possible the IP address or subnet is merged with other
        members of the set to form more concise CIDR blocks.

        :param addr: An IP address or subnet in either string or object form, or
            an IPRange object.

        :param flags: decides which rules are applied to the interpretation
            of the addr value. See the netaddr.core namespace documentation
            for supported constant values.

        """
        if isinstance(addr, IPRange):
            new_cidrs = dict.fromkeys(iprange_to_cidrs(addr[0], addr[-1]),
                                      True)
            self._cidrs.update(new_cidrs)
            self.compact()
            return
        if isinstance(addr, IPNetwork):
            # Networks like 10.1.2.3/8 need to be normalized to 10.0.0.0/8
            addr = addr.cidr
        elif isinstance(addr, _int_type):
            addr = IPNetwork(IPAddress(addr, flags=flags))
        else:
            addr = IPNetwork(addr)

        self._cidrs[addr] = True
        self._compact_single_network(addr)
Exemplo n.º 16
0
    def __init__(self, iterable=None, flags=0):
        """
        Constructor.

        :param iterable: (optional) an iterable containing IP addresses and
            subnets.

        :param flags: decides which rules are applied to the interpretation
            of the addr value. See the netaddr.core namespace documentation
            for supported constant values.

        """
        if isinstance(iterable, IPNetwork):
            self._cidrs = {iterable.cidr: True}
        elif isinstance(iterable, IPRange):
            self._cidrs = dict.fromkeys(
                iprange_to_cidrs(iterable[0], iterable[-1]), True)
        elif isinstance(iterable, IPSet):
            self._cidrs = dict.fromkeys(iterable.iter_cidrs(), True)
        else:
            self._cidrs = {}
            if iterable is not None:
                mergeable = []
                for addr in iterable:
                    if isinstance(addr, _int_type):
                        addr = IPAddress(addr, flags=flags)
                    mergeable.append(addr)

                for cidr in cidr_merge(mergeable):
                    self._cidrs[cidr] = True
Exemplo n.º 17
0
    def update(self, data):
        """
        Callback function used by Publisher to notify this Subscriber about
        an update. Stores topic based information into dictionary passed to
        constructor.
        """
        data_id = data[self.unique_key]

        if self.topic == 'IPv4':
            cidr = IPNetwork(cidr_abbrev_to_verbose(data_id))
            self.dct[cidr] = data
        elif self.topic == 'IPv6':
            cidr = IPNetwork(cidr_abbrev_to_verbose(data_id))
            self.dct[cidr] = data
        elif self.topic == 'multicast':
            iprange = None
            if '-' in data_id:
                #   See if we can manage a single CIDR.
                (first, last) = data_id.split('-')
                iprange = IPRange(first, last)
                cidrs = iprange.cidrs()
                if len(cidrs) == 1:
                    iprange = cidrs[0]
            else:
                iprange = IPAddress(data_id)
            self.dct[iprange] = data
Exemplo n.º 18
0
    def getTreeElem(self, ip):
        """
        Returns a tuple with the node that contains <ip> and the containing
        RBTree that contains this node. Return (None, RBTree) if no such node
        exists.

        Note that node.value is an IPBlock object.
        """
        iptree = self._findTree(ip)
        """
        find the IPBlock in the tree that starts at an IP address that is
        closest to <ip>, and SMALLER than <ip>
        """
        treeElem = iptree.findClosestNode(int(IPAddress(ip)))

        if not treeElem:
            return None, iptree
        """
        let's see if this is the 'right' closest block, i.e. the one where
        <ip> is >= the start IP of the block. if this is not the case, we
        pick the block's left neighbor.
        """
        if not ip in treeElem.value:
            treeElem = iptree.prevNode(treeElem)
            if not treeElem or not ip in treeElem.value:
                return None, iptree
            return treeElem, iptree
        else:
            return treeElem, iptree
Exemplo n.º 19
0
    def ipv6_link_local(self):
        """
        .. note:: This poses security risks in certain scenarios. \
            Please read RFC 4941 for details. Reference: RFCs 4291 and 4941.

        :return: new link local IPv6 `IPAddress` object based on this `EUI` \
            using the technique described in RFC 4291.
        """
        int_val = 0xfe800000000000000000000000000000

        if self.version == 48:
            # Convert 11:22:33:44:55:66 into 11:22:33:FF:FE:44:55:66.
            first_three = self._value >> 24
            last_three = self._value & 0xffffff
            int_val += (first_three << 40) | 0xfffe000000 | last_three
        else:
            int_val += self._value

        # Modified EUI-64 format interface identifiers are formed by inverting
        # the "u" bit (universal/local bit in IEEE EUI-64 terminology) when
        # forming the interface identifier from IEEE EUI-64 identifiers.  In
        # the resulting Modified EUI-64 format, the "u" bit is set to one (1)
        # to indicate universal scope, and it is set to zero (0) to indicate
        # local scope.
        int_val ^= 0x00000000000000000200000000000000

        return IPAddress(int_val, version=6)
Exemplo n.º 20
0
 def _findTree(self, ip):
     """
     returns the tree containing <ip>
     ip in integer or string format
     """
     ipnw = IPNetwork(str(IPAddress(ip)) + self.netmask).first
     return self.forest[ipnw]
Exemplo n.º 21
0
def announceRoutes(n):
    if ipVersion is 'ipv4':
        target = 'announce route 100.0.0.0/24 next-hop 90.0.0.1'
        FIR = 1
        SEC = 0
        THI = 0
        # generate n random ipv4 addresses and create a list
        for i in range(0, n):
            messages.append("announce route " + str(FIR) + "." + str(SEC) +
                            "." + str(THI) + ".0/24" + " next-hop 90.0.0.1")
            THI = THI + 1
            if THI == 254:
                SEC = SEC + 1
                THI = 0
            if SEC == 254:
                FIR = FIR + 1
                SEC = 0
    else:
        target = 'announce route 10::/64 next-hop 90::1'
        # generate n random ipv6 addresses
        for i in range(0, n):
            random.seed(i)
            ip_a = IPAddress('2001::cafe:0') + random.getrandbits(16)
            ip_n = IPNetwork(ip_a)
            messages.append('announce route ' + str(ip_n) + ' 90::1')
    # target at beginning or end of list
    if append == "first":
        messages.inser(0, target)
    else:
        messages.append(target)
    return messages
Exemplo n.º 22
0
 def __contains__(self, ip):
     """
     returns True only if <ip> is contained in this block's IP addresses
     """
     if IPAddress(ip) in self.iprange:
         return True
     else:
         return False
Exemplo n.º 23
0
def test_pretty_hex():
    # Arrange
    value = IPAddress("10.0.0.1")

    # Act
    result = utils.pretty_hex(value)

    # Assert
    assert result == "0A000001"
Exemplo n.º 24
0
def _parse_ip(ip, strict_format=None):
    if strict_format == 4 and not valid_ip_v4(ip):
        return None
    elif strict_format and strict_format != 4:
        raise NotImplementedError(
            "Ip format {} validation not supported.".format(strict_format))
    try:
        return IPAddress(ip)
    except:
        return None
Exemplo n.º 25
0
def prepare_migration_attachments_ipv6(system_service):
    hosts_service = system_service.hosts_service()

    for index, host in enumerate(test_utils.hosts_in_cluster_v4(
            system_service, CLUSTER_NAME),
                                 start=1):
        host_service = hosts_service.host_service(id=host.id)

        ip_address = MIGRATION_NETWORK_IPv6_ADDR.format(index)

        ip_configuration = network_utils_v4.create_static_ip_configuration(
            ipv6_addr=ip_address, ipv6_mask=MIGRATION_NETWORK_IPv6_MASK)

        network_utils_v4.modify_ip_config(system_service, host_service,
                                          MIGRATION_NETWORK, ip_configuration)

        actual_address = next(nic
                              for nic in host_service.nics_service().list()
                              if nic.name == VLAN200_IF_NAME).ipv6.address
        assert IPAddress(actual_address) == IPAddress(ip_address)
Exemplo n.º 26
0
def prepare_migration_attachments_ipv6(api_v4_connection):
    engine = api_v4_connection.system_service()

    for index, host in enumerate(test_utils.hosts_in_cluster(
            engine, CLUSTER_NAME),
                                 start=1):
        host_service = engine.hosts_service().host_service(id=host.id)

        ip_address = VLAN200_NET_IPv6_ADDR.format(index)

        ip_configuration = network_utils_v4.create_static_ip_configuration(
            ipv6_addr=ip_address, ipv6_mask=VLAN200_NET_IPv6_MASK)

        network_utils_v4.modify_ip_config(engine, host_service, VLAN200_NET,
                                          ip_configuration)

        actual_address = next(nic
                              for nic in host_service.nics_service().list()
                              if nic.name == VLAN200_IF_NAME).ipv6.address
        nt.assert_equals(IPAddress(actual_address), IPAddress(ip_address))
Exemplo n.º 27
0
def _parse_nmap_target_spec(target_spec):
    if '/' in target_spec:
        _, prefix = target_spec.split('/', 1)
        if not (0 < int(prefix) < 33):
            raise AddrFormatError('CIDR prefix expected, not %s' % prefix)
        net = IPNetwork(target_spec)
        if net.version != 4:
            raise AddrFormatError('CIDR only support for IPv4!')
        for ip in net:
            yield ip
    elif ':' in target_spec:
        #   nmap only currently supports IPv6 addresses without prefixes.
        yield IPAddress(target_spec)
    else:
        octet_ranges = _generate_nmap_octet_ranges(target_spec)
        for w in octet_ranges[0]:
            for x in octet_ranges[1]:
                for y in octet_ranges[2]:
                    for z in octet_ranges[3]:
                        yield IPAddress("%d.%d.%d.%d" % (w, x, y, z), 4)
Exemplo n.º 28
0
def ipv6_to_base85(addr):
    """Convert a regular IPv6 address to base 85."""
    ip = IPAddress(addr)
    int_val = int(ip)

    remainder = []
    while int_val > 0:
        remainder.append(int_val % 85)
        int_val //= 85

    return ''.join([BASE_85[w] for w in reversed(remainder)])
Exemplo n.º 29
0
def add_interface_vlan_data(target_vlan, int_vlan_data):
    vrrp_group = None
    for line in int_vlan_data[1:]:
        if vrrp_group is not None and not line.startswith("  "):
            vrrp_group = False

        if regex.match("^ ip address ([^\s]*)", line):
            target_vlan.ips.append(
                BrocadeIPNetwork(regex[0],
                                 is_secondary=line.endswith("secondary")))
        elif regex.match("^ ip access-group ([^\s]*) ([^\s]*)", line):
            direction = {'in': IN, 'out': OUT}[regex[1]]
            target_vlan.access_groups[direction] = regex[0]
        elif regex.match("^ vrf forwarding ([^\s]*)", line):
            target_vlan.vrf_forwarding = regex[0]
        elif regex.match("^ ip vrrp-extended vrid ([^\s]*)", line):
            vrrp_group = next((group for group in target_vlan.vrrp_groups
                               if str(group.id) == regex[0]), None)
            if vrrp_group is None:
                vrrp_group = VrrpGroup(id=int(regex[0]))
                target_vlan.vrrp_groups.append(vrrp_group)
        elif regex.match("^  ip-address ([^\s]*)", line):
            vrrp_group.ips.append(IPAddress(regex[0]))
        if vrrp_group:
            if regex.match(
                    "^  backup priority ([^\s]*) track-priority ([^\s]*)",
                    line):
                vrrp_group.priority = int(regex[0])
                vrrp_group.track_decrement = int(regex[1])
            elif regex.match("^  hello-interval ([^\s]*)", line):
                vrrp_group.hello_interval = int(regex[0])
            elif regex.match("^  dead-interval ([^\s]*)", line):
                vrrp_group.dead_interval = int(regex[0])
            elif regex.match("^  track-port (.*)", line):
                vrrp_group.track_id = regex[0]
            elif regex.match("^  activate", line):
                vrrp_group = None
        elif regex.match("^ ip helper-address ([^\s]*)", line):
            target_vlan.dhcp_relay_servers.append(IPAddress(regex[0]))
        elif regex.match("^ no ip redirect", line):
            target_vlan.icmp_redirects = False
Exemplo n.º 30
0
    def remove(self, addr, flags=0):
        """
        Removes an IP address or subnet or IPRange from this IP set. Does
        nothing if it is not already a member.

        Note that this method behaves more like discard() found in regular
        Python sets because it doesn't raise KeyError exceptions if the
        IP address or subnet is question does not exist. It doesn't make sense
        to fully emulate that behaviour here as IP sets contain groups of
        individual IP addresses as individual set members using IPNetwork
        objects.

        :param addr: An IP address or subnet, or an IPRange.

        :param flags: decides which rules are applied to the interpretation
            of the addr value. See the netaddr.core namespace documentation
            for supported constant values.

        """
        if isinstance(addr, IPRange):
            cidrs = iprange_to_cidrs(addr[0], addr[-1])
            for cidr in cidrs:
                self.remove(cidr)
            return

        if isinstance(addr, _int_type):
            addr = IPAddress(addr, flags=flags)
        else:
            addr = IPNetwork(addr)

        #   This add() is required for address blocks provided that are larger
        #   than blocks found within the set but have overlaps. e.g. :-
        #
        #   >>> IPSet(['192.0.2.0/24']).remove('192.0.2.0/23')
        #   IPSet([])
        #
        self.add(addr)

        remainder = None
        matching_cidr = None

        #   Search for a matching CIDR and exclude IP from it.
        for cidr in self._cidrs:
            if addr in cidr:
                remainder = cidr_exclude(cidr, addr)
                matching_cidr = cidr
                break

        #   Replace matching CIDR with remaining CIDR elements.
        if remainder is not None:
            del self._cidrs[matching_cidr]
            for cidr in remainder:
                self._cidrs[cidr] = True