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)])