Post Image

Python Generate Random MAC Address

When sanitizing output for this website I find myself replacing MAC addresses of various types such as colon separated, dot separated, and hyphen separated. I found that I needed a quick way of generating an arbitrary amount of MAC addresses so I decided to make a function in Python and tie it in with a command line script that allows me to generate any number MAC address of any format. In this post I will walk though the code I came up with to do that.

 

Generating a MAC Address

Below I have the function that is able to create a MAC address.

from random import randint


def random_mac(separator_char=':', separator_spacing=2):
    unseparated_mac = ''.join([hex(randint(0, 255))[2:].zfill(2) for _ in range(6)])
    return f'{separator_char}'.join(unseparated_mac[i:i + separator_spacing] for i in range(0, len(unseparated_mac), separator_spacing))

We do need to be able to generate a random integer so we import the randint function.

I then define the random_mac function which takes 2 arguments: the separator character which is default to a colon, and the spacing of that character which is set to 2 by default. By knowing this our function will create a MAC address formatted like 98:8c:59:76:c2:4b by default.

In the function the first line of code generates the raw data of the MAC address unseparated ex. b6ea731e9c75

Then the second line steps through the string and drops in the separator character at its required spacing. 

 

At this point we have a function we could run every time we need a MAC address but to make it more user friendly for me I created a command line application with argparse to be able to manipulate the parameters at runtime and be able to generate multiple MAC addresses at once.

if __name__ == '__main__':

    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('-sep', help='Separator character in MAC address', default=':', type=str)
    parser.add_argument('-spacing', help='Number of characters apart in MAC address to place separator character',
                        default=2, type=int)
    parser.add_argument('num', help='Number of MAC addresses to generate', type=int)
    args = parser.parse_args()

    for x in range(args.num):
        print(random_mac(separator_char=args.sep, separator_spacing=args.spacing))

Stepping through this we define 2 optional arguments -sep and -spacing which mirror the default arguments of my random_mac function. So the CLI application will generate the same format MAC address. 

I then define a required argument num which is the number of MAC addresses to generate.

Lastly the functionality of the application is implemented by a single for loop, which will loop the number of times specified in the num argument, and printing out a MAC address with the format specified by the separator and spacing

 

Below I have a few various ways of running the script and the various output you can expect to get.

$ python macgen.py 2
16:6c:d3:81:8f:1a
ef:99:67:c8:fe:09

$ python macgen.py 2 -sep . -spacing 4
4360.c424.a3de
4fe1.7e70.4bf7

$ python macgen.py 2 -sep -
ef-8f-9b-68-30-5e
34-30-a8-6f-11-9e

$ python macgen.py 2 -sep . -spacing 3
84c.b1c.c98.e3f
12b.9da.a81.8fd

$

 

I have the full script below if you would like to copy and paste it, running in your environment.

from random import randint


def random_mac(separator_char=':', separator_spacing=2):
    unseparated_mac = ''.join([hex(randint(0, 255))[2:].zfill(2) for _ in range(6)])
    return f'{separator_char}'.join(unseparated_mac[i:i + separator_spacing] for i in range(0, len(unseparated_mac), separator_spacing))


if __name__ == '__main__':

    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument('-sep', help='Separator character in MAC address', default=':', type=str)
    parser.add_argument('-spacing', help='Number of characters apart in MAC address to place separator character',
                        default=2, type=int)
    parser.add_argument('num', help='Number of MAC addresses to generate', type=int)
    args = parser.parse_args()

    for x in range(args.num):
        print(random_mac(separator_char=args.sep, separator_spacing=args.spacing))

 

If you have any questions please leave a comment so I can clear up any confusion.

 



Comments (0)
Leave a Comment