Better way of formatting Mac Addresses in Python

Following up on my Formating mac addresses using python post I have a better way of using Mac addresses.  I have been using the netaddr library for ip and mac address manipulations.  To convert a binary mac address to an EUI object you can use the following code

import netaddr
from netaddr import EUI

def convertMac(octet):
"""
This Function converts a binary mac address to a hexadecimal string representation
"""
return EUI(netaddr.strategy.eui48.packed_to_int(octet))

with the EUI object you have multiple options to format with.

>>> from netaddr import EUI
>>> import netaddr
>>> mac = EUI('01-23-45-67-89-0A')
>>> print mac
01-23-45-67-89-0A
>>>
>>> mac.dialect = netaddr.mac_cisco
>>> print mac
0123.4567.890a
>>>
>>> mac.dialect = netaddr.mac_unix
>>> print mac
1:23:45:67:89:a
>>>
>>> mac.dialect = netaddr.mac_bare
>>> print mac
01234567890A
>>>
>>> mac.dialect = netaddr.mac_unix_expanded
>>> print mac
01:23:45:67:89:0a
>>> mac.dialect = netaddr.mac_eui48
>>> print mac
01-23-45-67-89-0A

Leave a Reply

Your email address will not be published.