每次打开笔记本电脑时都会产生随机的 MAC 地址

每次打开笔记本电脑时都会产生随机的 MAC 地址

我希望每次打开笔记本电脑时自动获取随机 mac 地址。如有任何帮助,我将不胜感激。

PS 如果每次启动时都可以使用随机主机名就太好了。

答案1

您可以将以下内容添加为 root 的 cron 作业来运行@reboot。对于 cron,如何查看社区维基

笔记:您可能需要修改 Python 脚本,因为我还没有测试过它

#!/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()

相关内容