Translate in Your language

Friday, 13 March 2020

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. <filename>.py --interface <interface name> --newmac <new mac address>

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.

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


Other versions of this code:

GUI based
Basic

No comments:

Post a comment

Followers

Popular Posts This Week