Generate MAC Address by Scripts

In virtualized environment, we sometimes need to generate MAC address for each virtual machine at the time of creation. Since is a nearly unlimited amount of numbers on the same subnet, it is almost impossible that we would get the same MAC address. In the follwing paragraph, we’ll show you how to generate random MAC address by Python, Perl and Shell script.

Before that, let’s have a quick review on the Ethernet hardware address definition. Ethernet hardware addresses (a.k.a MAC Address, or Physical address) are 48 bits, expressed as 12 hexadecimal digits (0-9, plus A-F). These 12 hex digits consist of the first/left 6 digits, which should match the vendor of the Ethernet interface within the station, and the last/right 6 digits which specify the interface serial number for that interface vendor.

The following python code can be used to generate a MAC address, and it’s a little different from the second one as the vendor code is predefined in script:

#! /usr/bin/python
# Filename: macgen.py
# Usage: It's intended to generate MAC addresses for virtualized
#        systems that created by Xen, OpenVZ, Vserver etc.

import random

# The first line is defined for specified vendor
mac = [ 0x00, 0x24, 0x81,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]

print ':'.join(map(lambda x: "%02x" % x, mac))

An generated example is here: 00:24:81:6a:0d:7a

With the help of the next Perl script, we can generate fully random mac address or use a list to get the first 6 vendor codes and generate the last 6 random digits. A full vendor codes list is available here.

#!/usr/bin/perl -w
# Feed the vendor list with stdin, or add random parameter for fully random
#

use strict;

my ( %vendor, $lladdr, $i ); $ = "n";
my $c = ( defined $ARGV [ 0 ] ) ? 10 : 6;

if( $c == 6 )
{
  while ( <STDIN> )
  {
    chomp $_;
    $_ =~ s/^( [0-9a-f] {2} ) (?: s | : ) ? ( [0-9a-f] {2} ) (?: s | : ) ?
	   ( [0-9a-f] {2} ) (?: (?: s* ) | (?: (?: s+ ) ( .+ ) ) ? )$/
	    $vendor{ "$1:$2:$3" } = $4 || 'N/A';
	  /eix;
  } close STDIN;

  my @keys = keys % vendor or exit ( 1 );
  $lladdr = $keys [ rand @keys ];
  print "Vendor: $vendor{ $lladdr }";
}
else
{
  $lladdr = '00';
}

while ( ++$i )
{
  last if $i > $c; $lladdr .= ':' if $i % 2;
  $lladdr .= sprintf "%" . ( qw (X x) [int  ( rand ( 2 ) ) ] ), int ( rand ( 16 ) );
}

print  "MAC Address: $lladdr";
exit (0);

Easyvmx.com maintained a shell script to do similar thing, and it’s released under BSD license and more functional than the above two scripts. You can download it here:
http://www.easyvmx.com/software/easymac.sh

Share Button

One thought on “Generate MAC Address by Scripts

Leave a comment

Your email address will not be published. Required fields are marked *