So, what is a mac address? This can be either physical or virtual. This can be identified by the manufacturer to ensure that all of the custom machines are unique. The mac address of a machine, then again, could be examined using a network card and the right software. In this tutorial, we’ll discuss how to update your mac address using Python.

How to Update Youd Mac Address using Python in Windows

import subprocess
import winreg
import re
import codecs

Create a variable to store the list of the mac address

mac_to_change_to = ["0A1122334455", "0E1122334455", "021122334455", "061122334455"]

Create an empty list to store all the MAC addresses that we want to collect

mac_addresses = list()

We start off by creating a regular expression (regex) for MAC addresses, then We create a regex for the transport names And then We create a regex to pick out the adapter index.

macAddRegex = re.compile(r"([A-Za-z0-9]{2}[:-]){5}([A-Za-z0-9]{2})")
transportName = re.compile("({.+})")
adapterIndex = re.compile("([0-9]+)")

We use Python to run the getmac command, and then capture the output then We split the output at the new line so that we can work with the individual lines.

getmac_output = subprocess.run("getmac", capture_output=True).stdout.decode().split('\n')

Here we loop through the output to use the regex to find the Mac Addresses and then we use the regex to find the transport name

for macAdd in getmac_output:
    macFind = macAddRegex.search(macAdd)
    transportFind = transportName.search(macAdd)
    if macFind == None or transportFind == None:
        continue
    mac_addresses.append((macFind.group(0),transportFind.group(0)))

Create a simple menu to select which Mac Address the user wants to update.

print("select the MAC Address want to update")
for index, item in enumerate(mac_addresses):
    print(f"{index} - Mac Address: {item[0]} - Transport Name: {item[1]}")

Prompt the user to select Mac Address they want to update

option = input("Select the number of the MAC address you want to change:")

Create a simple console that lets the user select the MAC address. If the user selects a valid MAC address, replace it. Otherwise, give an error to make sure only valid ones are chosen.

while True:
    print("Which MAC address would you like us to use? ")
    for index, item in enumerate(mac_to_change_to):
        print(f"{index} - Mac Address: {item}")

    update_option = input("Select the item number of the new MAC address you want to use:")
    if int(update_option) >= 0 and int(update_option) < len(mac_to_change_to):
        print(f"Mac Address you selected: {mac_to_change_to[int(update_option)]}")
        break
    else:
        print("this address is not valid, please select different address")

We know the first part of the key, we’ll append the folders where we’ll search the values

controller_key_part = r"SYSTEM\ControlSet001\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}"

We connect to the HKEY_LOCAL_MACHINE registry. If we specify None, it means we connect to the local machine’s registry

with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:

Create a list for the 21 folders to makes use of a ternary operator. The transport value for your Mac Address should fall within this range.’

    controller_key_folders = [("\\000" + str(item) if item < 10 else "\\00" + str(item)) for item in range(0, 21)]

We now iterate through the list of folders we created and try to open the key. Then we have to specify the registry we connected to 

  for key_folder in controller_key_folders:
        try:
            with winreg.OpenKey(hkey, controller_key_part + key_folder, 0, winreg.KEY_ALL_ACCESS) as regkey:
                try:
                    count = 0
                    while True:
                        name, value, type = winreg.EnumValue(regkey, count)
                        count = count + 1
                        if name == "NetCfgInstanceId" and value == mac_addresses[int(option)][1]:
                            new_mac_address = mac_to_change_to[int(update_option)]
                            winreg.SetValueEx(regkey, "NetworkAddress", 0, winreg.REG_SZ, new_mac_address)
                            print("Successfully matched Transport Number")
                            break
                except WindowsError:
                    pass
        except:
            pass

Now we have to disable and enable Wireless devices

run_disable_enable = input("Do you want to disable and re-enable your wireless device(s). Press Y or y to continue:")
# Changes the input to lowercase and compares it to Y. If they match, the rest of the function will run. And if they don’t then function will never run
if run_disable_enable.lower() == 'y':
    run_last_part = True
else:
    run_last_part = False
# The `run_last_part` variable should be set to True or False based on above code
while run_last_part:

Now we have to disable and enable the network adapters

Note: if we get a list of all network adapters and it has an error you have to ignore the errors because it doesn’t like the format the command returns the data in.

    network_adapters = subprocess.run(["wmic", "nic", "get", "name,index"], capture_output=True).stdout.decode('utf-8', errors="ignore").split('\r\r\n')
    for adapter in network_adapters:
        # getting the index for each of the adapter available
        adapter_index_find = adapterIndex.search(adapter.lstrip())
        # If the user's adapter has wireless in its description, we're going to toggle it off and on.
        if adapter_index_find and "Wireless" in adapter:
            disable = subprocess.run(["wmic", "path", "win32_networkadapter", "where", f"index={adapter_index_find.group(0)}", "call", "disable"],capture_output=True)
            if(disable.returncode == 0):
                print(f"Disabled {adapter.lstrip()}")
            # enable the network adapter again.
            enable = subprocess.run(["wmic", "path", f"win32_networkadapter", "where", f"index={adapter_index_find.group(0)}", "call", "enable"],capture_output=True)
            if (enable.returncode == 0):
                print(f"Enabled {adapter.lstrip()}")

Run the getmac command again to check if the MAC address we changed to is among the list returned by running “getmac”. If it’s present, we’ve been successful.

    getmac_output = subprocess.run("getmac", capture_output=True).stdout.decode()
    mac_add = "-".join([(mac_to_change_to[int(update_option)][i:i+2]) for i in range(0, len(mac_to_change_to[int(update_option)]), 2)])
    if mac_add in getmac_output:
        print("Mac Address Success")
    break

And that it now we can run to code to change the mac address

Note: before running the code make sure to open your command prompt with the Run as administrator and also connect to a wireless network.

Output:

How to update your Mac address using Python in Linux

First, let’s check the current mac address. For that, you can use the following command in your terminal

Ifconfig

Now let’s see how to update your Mac address using Python:

import dependencies

import subprocess

Add your name of the network

interface = "wlan0"

Add the new mac address that you want to change

mac = "00:11:11:11:11:07"

Now let’s take down the network 

subprocess.call(["ifconfig", interface, "down"])

Now change the mac address

subprocess.call(["ifconfig", interface, "hw", "ether", mac])

And lastly, let’s up the network

subprocess.call(["ifconfig", interface, "up"])

Now to run the code open the terminal in the same directory where your python file is then run the code.

Output:

Before changing the mac address

After changing the mac address

Final Words

We hope you enjoyed our article on how to update your mac address using Python and found it valuable. We know that in the modern world, technology is everywhere, so this means that our computers are used for various purposes. Although computers have a variety of purposes, they are all linked in some way. If you have any questions or comments about this blog, please do not hesitate to contact us at.

Here are some useful tutorials that you can read: