0

I built a class to change my mac address (not sure if this is the cleanest way to do so)

#!/usr/bin/env python3
import subprocess


class MacAdress:

    global interface

    interface = input("enter interface:\t")

    def change_Mac(self=interface):
        mac = '00:11:22:ff:ff:ff'
        subprocess.call(f"sudo -S ifconfig {interface} down", shell=True)
        subprocess.call(f'sudo -S ifconfig {interface} hw ether {mac}', shell=True)
        subprocess.call(f"sudo -S ifconfig {interface} up", shell=True)

    def Restore_Mac(self=interface):
        old_mac = ''
        subprocess.call(f"sudo -S ifconfig {interface} down", shell=True)
        subprocess.call(f'sudo -S ifconfig {interface} hw ether {old_mac}', shell=True)
        subprocess.call(f"sudo -S ifconfig {interface} up", shell=True)

I was wondering if there is a way to store the root password so it only prompts one time similar to how interface is used, instead of using sudo -S for each command.old mac is left blank intentionally. Any tips for cleaning this up to be more professional would be greatly appreciated as well.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • You don't want to or need to run sudo inside the script. Just run commands without sudo, and run *your* script with sudo. – Jim Stewart Sep 22 '20 at 00:08

1 Answers1

0
#!/usr/bin/env python3
import subprocess, optparse, getpass


def get_arguments():
    parser = optparse.OptionParser()
    parser.add_option("-i", "--interface", dest="interface", help="Interface to change MAC address eg. eth0 wlan0")
    parser.add_option("-m", "--mac", dest="new_mac", help="New Mac Address")
    (options, arguments) = parser.parse_args()
    if not options.interface:
        parser.error("Please specify an interface with -i or --interface use --help for more info")

    elif not options.new_mac:
        parser.error("Please specify an new mac with -m or --mac use --help for more info")

    return options


def change_mac(interface, new_mac):
    cmd1 = "ifconfig " + interface + " down"
    cmd2 = "ifconfig " + interface + " hw" + " ether " + new_mac
    cmd3 = "ifconfig " + interface + " up"
    root_password = getpass.getpass("Enter Sudo password : ")
    print(f"[+] Changing MAC address for " + interface + " to " + new_mac)
    subprocess.call('echo {} | sudo -S {}'.format(root_password, cmd1), shell=True)
    subprocess.call('echo {} | sudo -S {}'.format(root_password, cmd2), shell=True)
    subprocess.call('echo {} | sudo -S {}'.format(root_password, cmd3), shell=True)


options = get_arguments()
change_mac(options.interface, options.new_mac)

Figured it out looks documentation provided enough information to answer my question along with some off topic linux-cli answers on Stack Overflow. Great community!!!

~edit~ It looks like there is a better way to capture the sudo password that wont show in clear text using the getpass library and passing arguments in cli