Skip to content

Instantly share code, notes, and snippets.

@linickx linickx/convertmac.py
Last active Aug 29, 2015

Embed
What would you like to do?
Python and MAC addresses
#!/usr/bin/env python
# My Post: http://www.linickx.com/3970/python-and-mac-addresses
# REF: http://craigbalfour.blogspot.co.uk/2008/10/normalizing-mac-address-string.html
# REF http://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/
# Lib
import sys, getopt
# Function
def printhelp():
print("Usage: %s -m MAC " % sys.argv[0])
print("\n MAC can be in any of the following formats: ")
print(" - 00:00:00:00:00:00")
print(" - 00-00-00-00-00-00")
print(" - 0000.0000.0000")
print("\n Version %s" % version)
# Defaults
addr=""
version="1.02"
defaultoutput=True
printcisco=False
printeui=False
printms=False
# CLI input
try:
myopts, args = getopt.getopt(sys.argv[1:],"m:hces")
except getopt.GetoptError as e:
print (str(e))
printhelp()
sys.exit(2)
# o == option
# a == argument passed to the o
for o, a in myopts:
# m => Mac Address
if o == '-m':
addr=a
# h => Help
if o == '-h':
printhelp()
sys.exit()
# c => Cisco
if o == '-c':
printcisco=True
defaultoutput=False
# e => EUI
if o == '-e':
printeui=True
defaultoutput=False
# s => humm, microSoft
if o == '-s':
printms=True
defaultoutput=False
# No options pased, re-set default vars.
if defaultoutput:
printcisco=True
printeui=True
printms=True
# No mac from options, ask for it.
if addr == "":
addr = raw_input("Enter the MAC address: ")
# Determine which delimiter style out input is using
if "." in addr:
delimiter = "."
elif ":" in addr:
delimiter = ":"
elif "-" in addr:
delimiter = "-"
# Eliminate the delimiter
m = addr.replace(delimiter, "")
# Normalise Case
m = m.lower()
u = m.upper()
# convert!
# Cisco
if printcisco:
cisco= ".".join(["%s%s%s%s" % (m[i], m[i+1], m[i+2], m[i+3]) for i in range(0,12,4)])
if defaultoutput:
sys.stdout.write("Cisco: ")
print cisco
# EUI
if printeui:
eui= ":".join(["%s%s" % (m[i], m[i+1]) for i in range(0,12,2)])
if defaultoutput:
sys.stdout.write("EUI: ")
print eui
# MicroSoft
if printms:
ms= "-".join(["%s%s" % (u[i], u[i+1]) for i in range(0,12,2)])
if defaultoutput:
sys.stdout.write("Microsoft: ")
print ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.