Changing MAC address using Python code – parsing input instead of prompting

With this code you can directly pass input while running python script.

e.g. .py –interface –newmac

Copy below code and save it as .py file. Then run the python script to test. You can modify the code as required for your requirements like adding extra arguments.

Other versions of this code:

GUI based
Basic

# MAC Changer input parsing

import subprocess
import optparse

def mchange(iface, nmac):
    print("Changing the MAC Address as per the input")
    subprocess.call(["ifconfig", iface, "down"])
    subprocess.call(["ifconfig", iface, "hw", "ether", nmac])
    subprocess.call(["ifconfig", iface, "up"])
    print("MAC Address changed Successfully to: " + nmac)

varparser = optparse.OptionParser()
varparser.add_option("-i", "--interface", dest="iface", help="Interface Name")
varparser.add_option("-m", "--newmac", dest="nmac", help="New MAC Address")

(options, args) = varparser.parse_args()

iface = options.iface
nmac = options.nmac

mchange(options.iface, options.nmac)

Feel free to share if any errors/suggestions in code.

Above code can also be simplified using extra function.

import subprocess
import optparse

def mchange(iface, nmac):
    print("Changing the MAC Address as per the input")
    subprocess.call(["ifconfig", iface, "down"])
    subprocess.call(["ifconfig", iface, "hw", "ether", nmac])
    subprocess.call(["ifconfig", iface, "up"])
    print("MAC Address changed Successfully to: " + nmac)

def args():
    varparser = optparse.OptionParser()
    varparser.add_option("-i", "--interface", dest="iface", help="Changing the MAC Address of interface")
    varparser.add_option("-m", "--newmac", dest="nmac", help="New MAC Address")
    return varparser.parse_args()

(options, args) = args()
mchange(options.iface, options.nmac)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.