Python generates random MAC addresses

  • 2020-04-02 14:40:21
  • OfStack

Generate a random MAC address using python code, which may be available for network programming in python, or directly generate a MAC using the RandMAC() function if you use the scapy module.

python


import random
Maclist = []
for i in range(1,7):
    RANDSTR = "".join(random.sample("0123456789abcdef",2))
    Maclist.append(RANDSTR)
RANDMAC = ":".join(Maclist)
print RANDMAC
-------------------------------- The results -----------------------------------
e4:13:0e:1a:73:f5

The following Fake_HW is a MAC address packaged with a struct in binary format


import random
import struct
mac_bin_list = []
mac_hex_list = []
for i in range(1,7):
    i = random.randint(0x00,0xff)
    mac_bin_list.append(i)
Fake_HW = struct.pack("BBBBBB",mac_bin_list[0], mac_bin_list[1], mac_bin_list[2], mac_bin_list[3], mac_bin_list[4], mac_bin_list[5])
for j in mac_bin_list:
    mac_hex_list.append(hex(j))
Hardware = ":".join(mac_hex_list).replace("0x","")
print Hardware
-------------------- The results of -----------------------------
24:c7:6f:92:2c:42

That's all for this article, I hope you enjoy it.


Related articles: