|
| 1 | +import sys |
| 2 | +import subprocess |
| 3 | +import os |
| 4 | +import re |
| 5 | + |
| 6 | +# Check if the Operating System is Windows or not. |
| 7 | +WINDOWS = os.name != 'posix' |
| 8 | +mac_regex = ("^([0-9A-Fa-f]{2}[:-])" + |
| 9 | + "{5}([0-9A-Fa-f]{2})|" + |
| 10 | + "([0-9a-fA-F]{4}\\." + |
| 11 | + "[0-9a-fA-F]{4}\\." + |
| 12 | + "[0-9a-fA-F]{4})$") |
| 13 | + |
| 14 | +# Compile a regular expression to validate MAC addresses. |
| 15 | +mac_regex = re.compile(mac_regex) |
| 16 | + |
| 17 | +# Check if MAC address was supplied as a commandline argument. |
| 18 | +if len(sys.argv) < 2: |
| 19 | + sys.exit("Enter new MAC address as a commandline argument.") |
| 20 | + |
| 21 | +# Check if the supplied MAC address was valid or not. |
| 22 | +new_mac = sys.argv[1] |
| 23 | +if not re.search(mac_regex, new_mac): |
| 24 | + sys.exit("Please enter a valid MAC address.") |
| 25 | + |
| 26 | +# Perform different operations based on the operating system. |
| 27 | +if not WINDOWS: |
| 28 | + # Get the output containing necessary information. |
| 29 | + output = subprocess.getoutput('ip link show | grep "link/ether"').split() |
| 30 | + |
| 31 | + # Look for a valid MAC address. |
| 32 | + for entry in output: |
| 33 | + if re.search(mac_regex, entry): |
| 34 | + prev_mac = re.search(mac_regex, entry).group() |
| 35 | + break |
| 36 | + |
| 37 | + # Extract the nic device associated with the MAC address. |
| 38 | + nic_device = subprocess.getoutput('ip addr show | grep "altname"').split()[1] |
| 39 | + |
| 40 | + # Perform actions to change MAC address. |
| 41 | + subprocess.call(f'sudo ip link set dev {nic_device} down') |
| 42 | + subprocess.call(f'sudo ip link set dev {nic_device} address {new_mac}') |
| 43 | + subprocess.call(f'sudo ip link set dev {nic_device} up') |
| 44 | + |
| 45 | +else: |
| 46 | + # Get the appropriate output. |
| 47 | + output = subprocess.getoutput('getmac /v | findstr Device').split() |
| 48 | + |
| 49 | + # Check for a valid MAC address in output. |
| 50 | + for entry in output: |
| 51 | + if re.search(mac_regex, entry): |
| 52 | + prev_mac = re.search(mac_regex, entry).group() |
| 53 | + break |
| 54 | + |
| 55 | + # Extract the associated nic device. |
| 56 | + nic_device = output[-1][output[-1].find('{'):] |
| 57 | + |
| 58 | + # Perform actions to change MAC address. |
| 59 | + subprocess.call('reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\%s\0004 /v NetworkAddress /d %s /f'%format(nic_device, new_mac.replace(":", ""))) |
| 60 | + |
| 61 | + |
| 62 | +print(f"Old MAC address: \033[93m{prev_mac}\033[0m") |
| 63 | +print(f"New Mac address: \033[92m{new_mac}\033[0m") |
0 commit comments