Formating Mac addresses using python


A better way to do this is using the netaddr library.  as shown in this post Better way of formatting mac addresses in python


I have a large set of shell script that I had written in shell, which I have been converting to python based scripts.  I found using python I could better extend my scripts and reuse code.  I also appreciate that python is a full object oriented programming language, with a very powerful set of standard libraries and many optional third party libraries.

One of the first obstacles I ran into was choosing what snmp library to use for my scripts.  The two choices I had to pick from were pysnmp and the python bindings for net-snmp.  Out of these I choices I chose pysnmp for three primary reasons.  First, pysnmp was a native object-oriented python implementation.  Secondly, pysnmp supported asyncronus polling.  Last but definitively not least pysnmp’s implementation of a getNext(snmpwalk) or getBulk returned not just the values, but a list with both the oid polled as well at the value.  That last feature was a deal breaker for me since it allowed me to grab two different tables from a device and correlate the corresponding indexes.

as a close to this post a want to share two quick code snippits you can use to format mac addresses.

This first function converts the binary octal addresses that pysnmp returns when you poll a mac address oid

def convertMac(octet):
 This Function converts a binary mac address to a hexadecimal string representation
 mac = [binascii.b2a_hex(x) for x in list(octet)]
 return ":".join(mac)

The second function sanitizes a mac address string of any format and outputs one in the 01:23:45:67:89:0A format.

def sanitizeMac(mac):
 temp = mac.replace(":", "").replace("-", "").replace(".", "").upper()
 return temp[:2] + ":" + ":".join([temp[i] + temp[i+1] for i in range(2,12,2)])

5 Replies to “Formating Mac addresses using python”

  1. Your code requires an explicit import of the binascii module in Python 2.7.3. There are ‘encode’ and ‘decode’ string methods available that are syntactic sugar for the binascii.b2a() and binascii.a2b() methods that you get for free:

    def convertMac(octet):
    mac = [x.encode(“hex”) for x in list(octet)]
    return “:”.join(mac)

    A little more readable, and you don’t need to import binascii.

  2. Why use `return temp[:2] + “:” + “:”.join([temp[i] + temp[i+1] for i in range(2,12,2)])` instead of just `return “:”.join([temp[i:i+2] for i in range(0,12,2)])`? Both should do exactly the same as far as I can see.

Leave a Reply

Your email address will not be published.