3

I would like to get a random mac-address automatically every time I turn on my laptop. Any help is appreciated.

P.S. If at all possible a random hostname every startup would be great.

2

You could add the following as root's cron job to run @reboot. For cron how to see the community wiki

Note: You may have to alter the python script as i have not test it

#!/usr/bin/python
# the mac generating function is based from
#http://www.centos.org/docs/5/html/5.2/Virtualization/sect-Virtualization-Tips_and_tricks-Generating_a_new_unique_MAC_address.html
#
# Changes MAC address and Hostname using random values
# NOTE: This script must be called as root
# In case of adding it as cron job, it must be in root's cron jobs!
import random
import subprocess

mac = generate_mac()
hostname = generate_hostname()
proc = subprocess.Popen("/bin/hostname", shell=True, stdout=subprocess.PIPE)
old_hostname = subprocess.stdout.read()
interface = "eth0"
bring_if_down = "ifconfig {iface} down".format(iface=interface)
bring_if_up = "ifconfig {iface} up".format(iface=interface)
change_mc = "ifconfig {iface} hw ether".format(iface=interface)
change_hostname = "hostname {hostn}".format(hostn=hostname)

def generate_mac():
    mac = [
        random.randint(0x00, 0x7f),
        random.randint(0x00, 0x7f),
        random.randint(0x00, 0x7f),
        random.randint(0x00, 0x7f),
        random.randint(0x00, 0xff),
        random.randint(0x00, 0xff) ]
    return ':'.join(map(lambda x: "%02x" % x, mac))

def generate_hostname():

    _result = ""
    for x in range(8):
        _result += (random.choice("abcdefghijklmnopqrstuvwxyz"))

    return _result

def do_change():
    # bring interface down
    subprocess.Popen(bring_if_down)
    # change MAC address
    subprocess.Popen(change_mc)
    # change the host name
    subprocess.Popen(change_hostname)
    old_host = open("/etc/hostname", "r").read()
    with open("/etc/hostname", "r") as infile:
        data = []
        for line in infile.readlines():
            data.append(line.replace(old_hostname, hostname))

    with open("/etc/hostname", "w") as outfile:
        for line in data:
            outfile.write(line)

    # brin interface up
    subprocess.Popen(bring_if_up )

def main():
    do_change()

if __name__ == '__main__':
    main()
1
  • Any random combination of hex values does not constitute a valid MAC. – Him Aug 7 '19 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.