Python netaddr.EUI Examples

The following are 30 code examples of netaddr.EUI(). 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: test_sqlalchemytypes.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def test_crud(self):
        mac_addresses = ['FA:16:3E:00:00:01', 'FA:16:3E:00:00:02']

        for mac in mac_addresses:
            mac = netaddr.EUI(mac)
            self._add_row(id=uuidutils.generate_uuid(), mac=mac)
            obj = self._get_one(mac)
            self.assertEqual(mac, obj['mac'])
            random_mac = netaddr.EUI(net.get_random_mac(
                ['fe', '16', '3e', '00', '00', '00']))
            self._update_row(mac, random_mac)
            obj = self._get_one(random_mac)
            self.assertEqual(random_mac, obj['mac'])

        objs = self._get_all()
        self.assertEqual(len(mac_addresses), len(objs))
        self._delete_rows()
        objs = self._get_all()
        self.assertEqual(0, len(objs)) 
Example #2
Source File: evpn.py    From yabgp with Apache License 2.0 6 votes vote down vote up
def parse(cls, value, iswithdraw=False):
        route = dict()
        # rd
        offset = 8
        route['rd'] = cls.parse_rd(value[0:offset])
        # esi
        route['esi'] = int(binascii.b2a_hex(value[offset: offset+10]), 16)
        offset += 10
        # ethernet tag id
        route['eth_tag_id'] = struct.unpack('!I', value[offset: offset+4])[0]
        offset += 5
        # mac address
        route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset+6]), 16)))
        offset += 6
        ip_addr_len = ord(value[offset: offset + 1])
        offset += 1
        # ip address
        if ip_addr_len != 0:
            route['ip'] = str(netaddr.IPAddress(
                int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16)))
            offset += int(ip_addr_len / 8)
        # label
        route['label'] = MPLSVPN.parse_mpls_label_stack(value[offset:])
        return route 
Example #3
Source File: mac-lookup.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def run(self):
        mac = netaddr.EUI(int(self.arguments.mac) if self.arguments.mac.isdigit() else self.arguments.mac)
        info = mac.info["OUI"]
        print(f"[i] Media Access Control (MAC) Address Lookup Results For {mac}:")
        print(f" -  Extended Unique Identifier 64:       {mac.eui64()}", dark=True)
        print(f" -  Modified EUI64 Address:              {mac.modified_eui64()}", dark=True)
        print(f" -  Individual Access Block [IAB]:       {mac.iab if mac.is_iab() else 'Not an IAB'}", dark=True)
        print(f" -  Organizationally Unique Identifier:  {mac.oui}", dark=True)
        print(f" -  Extended Identifier [EI]:            {mac.ei}", dark=True)
        print(f" -  Local Link IPv6 Address:             {mac.ipv6_link_local()}", dark=True)
        print(f" -  Vendor Info.:")
        print(f"    - Organization: {info['org']}", dark=True)
        print( "    - Address:      {}".format("\n                    ".join(info["address"])), dark=True)
        print(f" -  OUI Info.:")
        print(f"    - Version: {mac.version}", dark=True)
        print(f"    - Offset:  {info['offset']}", dark=True)
        print(f"    - Size:    {info['size']}", dark=True)
        print(f"    - IDX:     {info['idx']}", dark=True)
        print(f"    - OUI:     {info['oui']}", dark=True)
        print(f" -  Packed Address:          {mac.packed}", dark=True)
        print(f" -  Hexadecimal Address:     {hex(mac)}", dark=True)
        print(f" -  48-bit Positive Integer: {mac.value}", dark=True)
        print(f" -  Octets:                  {', '.join(str(n) for n in mac.words)}", dark=True) 
Example #4
Source File: base_extras.py    From upribox with GNU General Public License v3.0 6 votes vote down vote up
def get_device_names(device):
    mac_vendor = None
    try:
        mac_vendor = EUI(device.mac).oui.registration().org
    except Exception:
        pass

    elems = [device.hostname]
    elems.extend([x.model for x in device.user_agent.all()])
    elems.append(mac_vendor)
    elems.append(device.mac)
    names = []
    # make unique sorted list
    [names.append(x) for x in elems if x not in names]

    return filter(lambda x: x not in IGNORE, names) 
Example #5
Source File: aplauncher.py    From EvilTwinFramework with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,  id=0, name=None, mac_address=None, ip_address=None,
                        connected_ssid=None, inactivity_time=None,
                        rx_packets=None, tx_packets=None,
                        rx_bitrate=None, tx_bitrate=None,
                        signal=None):

        self.id = id
        self.name = name
        self.mac_address = mac_address
        self.ip_address = ip_address
        self.connected_ssid = connected_ssid
        self.inactivity_time = inactivity_time
        self.rx_packets = rx_packets
        self.tx_packets = tx_packets
        self.tx_bitrate = tx_bitrate
        self.rx_bitrate = rx_bitrate
        self.signal = signal
        self.vendor = None
        try:
            self.vendor = EUI(mac_address).oui.registration().org      # OUI - Organizational Unique Identifier
        except Exception:
            pass 
Example #6
Source File: test_trunk_app.py    From dragonflow with Apache License 2.0 6 votes vote down vote up
def get_expected_matches(self):
        return [
            {
                'reg6': test_app_base.fake_local_port2.unique_key,
                'eth_src': netaddr.EUI('fa:16:3e:00:00:01'),
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_IP,
                'ipv4_src': netaddr.IPAddress('192.168.18.3'),
            }, {
                'reg7': 33,
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_IP,
            }, {
                'reg6': test_app_base.fake_local_port2.unique_key,
                'eth_src': netaddr.EUI('fa:16:3e:00:00:01'),
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_ARP,
                'arp_sha': netaddr.EUI('fa:16:3e:00:00:01'),
                'arp_spa': netaddr.IPAddress('192.168.18.3'),
            }, {
                'reg7': 33,
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_ARP,
            }
        ] 
Example #7
Source File: test_trunk_app.py    From dragonflow with Apache License 2.0 6 votes vote down vote up
def get_expected_actions(self):
        return [
            [
                SettingMock(reg6=33),
                SettingMock(metadata=17),
                SettingMock(eth_src=netaddr.EUI('fa:16:3e:00:00:01')),
                self.app.parser.NXActionResubmit(),
            ], [
                SettingMock(eth_dst=test_app_base.fake_local_port2.mac),
                SettingMock(reg7=test_app_base.fake_local_port2.unique_key),
                self.app.parser.NXActionResubmit(),
            ], [
                SettingMock(reg6=33),
                SettingMock(metadata=17),
                SettingMock(eth_src=netaddr.EUI('fa:16:3e:00:00:01')),
                SettingMock(arp_sha=netaddr.EUI('fa:16:3e:00:00:01')),
                self.app.parser.NXActionResubmit(),
            ], [
                SettingMock(eth_dst=test_app_base.fake_local_port2.mac),
                SettingMock(arp_tha=test_app_base.fake_local_port2.mac),
                SettingMock(reg7=test_app_base.fake_local_port2.unique_key),
                self.app.parser.NXActionResubmit(),
            ]
        ] 
Example #8
Source File: test_sg_app.py    From dragonflow with Apache License 2.0 6 votes vote down vote up
def _get_another_local_lport(self):
        fake_local_port = test_app_base.make_fake_local_port(
            id='fake_port2',
            topic='fake_tenant1',
            name='',
            unique_key=5,
            version=2,
            ips=[netaddr.IPAddress('10.0.0.10'),
                 netaddr.IPAddress('2222:2222::2')],
            subnets=['fake_subnet1'],
            macs=[netaddr.EUI('fa:16:3e:8c:2e:12')],
            lswitch='fake_switch1',
            security_groups=['fake_security_group_id1'],
            allowed_address_pairs=[],
            port_security_enabled=True,
            device_owner='compute:None',
            device_id='fake_device_id',
            # 'binding_profile': {},
            # 'binding_vnic_type': 'normal',
        )
        return fake_local_port 
Example #9
Source File: tc_static.py    From nmeta with Apache License 2.0 6 votes vote down vote up
def is_valid_macaddress(self, value_to_check):
        """
        Passed a prospective MAC address and check that
        it is valid.
        Return 1 for is valid IP address and 0 for not valid
        """
        try:
            result = EUI(value_to_check)
            if result.version != 48:
                self.logger.debug("Check of is_valid_macaddress on %s "
                        "returned false", value_to_check)
                return 0
        except:
            self.logger.debug("Check of "
                    "is_valid_macaddress on %s raised an exception",
                    value_to_check)
            return 0
        return 1 
Example #10
Source File: tc_static.py    From nmeta with Apache License 2.0 6 votes vote down vote up
def is_match_macaddress(self, value_to_check1, value_to_check2):
        """
        Passed a two prospective MAC addresses and check to
        see if they are the same address.
        Return 1 for both the same MAC address and 0 for different
        """
        try:
            if not EUI(value_to_check1) == EUI(value_to_check2):
                self.logger.debug("Check of "
                        "is_match_macaddress on %s vs %s returned false",
                        value_to_check1, value_to_check2)
                return 0
        except:
            self.logger.debug("Check of "
                    "is_match_macaddress on %s vs %s raised an exception",
                    value_to_check1, value_to_check2)
            return 0
        return 1 
Example #11
Source File: data_utils.py    From tempest-lib with 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 #12
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__returns_sender_for_request(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "00:00:00:00:00:00"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REQUEST,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_sender_ip), EUI(pkt_sender_mac))]
        ) 
Example #13
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__returns_sender_and_target_for_reply(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "02:03:04:05:06:07"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(),
            [
                (IPAddress(pkt_sender_ip), EUI(pkt_sender_mac)),
                (IPAddress(pkt_target_ip), EUI(pkt_target_mac)),
            ],
        ) 
Example #14
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__skips_null_target_ip_in_reply(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "0.0.0.0"
        pkt_target_mac = "02:03:04:05:06:07"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_sender_ip), EUI(pkt_sender_mac))]
        ) 
Example #15
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__skips_null_source_eui_in_reply(self):
        pkt_sender_mac = "00:00:00:00:00:00"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "02:03:04:05:06:07"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_target_ip), EUI(pkt_target_mac))]
        ) 
Example #16
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__skips_null_target_eui_in_reply(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "00:00:00:00:00:00"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_sender_ip), EUI(pkt_sender_mac))]
        ) 
Example #17
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_new_binding(self):
        bindings = {}
        ip = IPAddress("192.168.0.1")
        mac = EUI("00:01:02:03:04:05")
        vid = None
        event = update_bindings_and_get_event(bindings, vid, ip, mac, 0)
        self.assertThat(bindings, Equals({(vid, ip): {"mac": mac, "time": 0}}))
        self.assertThat(
            event,
            Equals(
                dict(
                    event="NEW",
                    ip=str(ip),
                    mac=format_eui(mac),
                    time=0,
                    vid=vid,
                )
            ),
        ) 
Example #18
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_properties(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "00:00:00:00:00:00"
        eth_src = "02:03:04:05:06:07"
        eth_dst = "ff:ff:ff:ff:ff:ff"
        arp_packet = make_arp_packet(
            pkt_sender_ip, pkt_sender_mac, pkt_target_ip, pkt_target_mac
        )
        arp = ARP(
            arp_packet,
            src_mac=hex_str_to_bytes(eth_src),
            dst_mac=hex_str_to_bytes(eth_dst),
        )
        self.assertThat(arp.source_eui, Equals(EUI(pkt_sender_mac)))
        self.assertThat(arp.target_eui, Equals(EUI(pkt_target_mac)))
        self.assertThat(arp.source_ip, Equals(IPAddress(pkt_sender_ip)))
        self.assertThat(arp.target_ip, Equals(IPAddress(pkt_target_ip))) 
Example #19
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_moved_binding(self):
        bindings = {}
        ip = IPAddress("192.168.0.1")
        mac1 = EUI("00:01:02:03:04:05")
        mac2 = EUI("02:03:04:05:06:07")
        vid = None
        update_bindings_and_get_event(bindings, vid, ip, mac1, 0)
        event = update_bindings_and_get_event(bindings, vid, ip, mac2, 1)
        self.assertThat(
            bindings, Equals({(vid, ip): {"mac": mac2, "time": 1}})
        )
        self.assertThat(
            event,
            Equals(
                dict(
                    event="MOVED",
                    ip=str(ip),
                    mac=format_eui(mac2),
                    time=1,
                    previous_mac=format_eui(mac1),
                    vid=vid,
                )
            ),
        ) 
Example #20
Source File: test_funcs_host.py    From NetworkML with Apache License 2.0 6 votes vote down vote up
def test_host_keys():
    test_data = {field: None for field in WS_FIELDS}
    eth_src = '0e:00:00:00:00:01'
    eth_src_int = int(netaddr.EUI(eth_src))
    src_ip = ipaddress.ip_address('192.168.0.1')
    dst_ip = ipaddress.ip_address('192.168.0.2')
    test_data.update({
        'ip.version': 4,
        'eth.src': eth_src_int,
        'eth.dst': eth_src_int,
        'ip.src': str(int(src_ip)),
        'ip.dst': str(int(dst_ip)),
        'tcp.srcport': 999,
        'tcp.dstport': 1001,
        'frame.protocols': 'eth:ip',
    })
    row = nan_row_dict(test_data)
    instance = Host()
    assert instance._host_key(row)[1:] == (str(src_ip), str(dst_ip), 1, 0, 1)
    instance = SessionHost()
    assert instance._host_key(row)[1:] == (str(src_ip), str(dst_ip), 1, 0, 1) 
Example #21
Source File: __init__.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def validate_mac_address(data, valid_values=None):
    """Validate data is a MAC address.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if the data is a valid MAC address, otherwise a human
        readable message as to why validation failed.
    """
    try:
        valid_mac = netaddr.valid_mac(validate_no_whitespace(data))
    except Exception:
        valid_mac = False

    if valid_mac:
        valid_mac = (not netaddr.EUI(data) in
                     map(netaddr.EUI, constants.INVALID_MAC_ADDRESSES))
    # TODO(arosen): The code in this file should be refactored
    # so it catches the correct exceptions. validate_no_whitespace
    # raises AttributeError if data is None.
    if not valid_mac:
        msg = _("'%s' is not a valid MAC address") % data
        LOG.debug(msg)
        return msg 
Example #22
Source File: network.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_eui_organization(eui):
    """Returns the registered organization for the specified EUI, if it can be
    determined. Otherwise, returns None.

    :param eui:A `netaddr.EUI` object.
    """
    try:
        registration = eui.oui.registration()
        # Note that `registration` is not a dictionary, so we can't use .get().
        return registration["org"]
    except UnicodeError:
        # See bug #1628761. Due to corrupt data in the OUI database, and/or
        # the fact that netaddr assumes all the data is ASCII, sometimes
        # netaddr will raise an exception during this process.
        return None
    except IndexError:
        # See bug #1748031; this is another way netaddr can fail.
        return None
    except NotRegisteredError:
        # This could happen for locally-administered MACs.
        return None 
Example #23
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_format_eui(self):
        self.assertThat(
            format_eui(EUI("0A-0B-0C-0D-0E-0F")), Equals("0a:0b:0c:0d:0e:0f")
        ) 
Example #24
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_eui_organization(self):
        mac_address = "48:51:b7:00:00:00"
        self.assertThat(
            get_eui_organization(EUI(mac_address)), IsNonEmptyString
        ) 
Example #25
Source File: test_arp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_refreshed_binding_within_threshold_does_not_emit_event(self):
        bindings = {}
        ip = IPAddress("192.168.0.1")
        mac = EUI("00:01:02:03:04:05")
        vid = None
        update_bindings_and_get_event(bindings, vid, ip, mac, 0)
        event = update_bindings_and_get_event(bindings, vid, ip, mac, 1)
        self.assertThat(bindings, Equals({(vid, ip): {"mac": mac, "time": 0}}))
        self.assertIsNone(event) 
Example #26
Source File: packet.py    From EvilTwinFramework with GNU General Public License v2.0 5 votes vote down vote up
def get_vendor(mac):
        if mac != "":
            maco = EUI(mac)                         # EUI - Extended Unique Identifier
            try:
                return maco.oui.registration().org  # OUI - Organizational Unique Identifier
            except:                                 # OUI not registered exception
                return None
        return None 
Example #27
Source File: test_network.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_eui_organization_returns_none_for_invalid_mac(self):
        organization = get_eui_organization(EUI("FF:FF:b7:00:00:00"))
        self.assertThat(organization, Is(None)) 
Example #28
Source File: interface.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _eui64_address(self, net_cidr):
        """Return the SLAAC address for this interface."""
        # EUI64 addresses are always /64.
        network = IPNetwork(net_cidr)
        if network.prefixlen != 64:
            return None
        return EUI(self.mac_address.raw).ipv6(network.first) 
Example #29
Source File: pandas_csv_importer.py    From NetworkML with Apache License 2.0 5 votes vote down vote up
def _netaddr_packed(val):
    if len(val) > 0:
        return int(netaddr.EUI(val))
    return None 
Example #30
Source File: device.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_Interface_from_list(interfaces, mac):
    """Return the `Interface` object with the given MAC address."""
    # Compare using EUI instances so that we're not concerned with a MAC's
    # canonical form, i.e. colons versus hyphens, uppercase versus lowercase.
    mac = EUI(mac)
    for interface in interfaces:
        ifmac = interface.mac_address
        if ifmac is not None and EUI(ifmac.raw) == mac:
            return interface
    else:
        return None