Last active
March 3, 2021 15:29
-
-
Save linickx/6516b5325098665a0898 to your computer and use it in GitHub Desktop.
Python and MAC addresses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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