How to randomly change the MAC on each boot in 16.04

Solution 1:

How to do it

Without any third party application, we can simply use NetworkManager's cli tool nmcli to change MAC address in terminal, scripts, etc.

nmcli connection modify enp3s0 802-3-ethernet.cloned-mac-address 02:7d:xx:xx:...
  • Change enp3s0 with your desired connection name, e.g: Home, Office Wi-Fi, etc.

If you are trying to clone a Wi-Fi connection then use 802-11-wireless.cloned-mac-address instead of 802-3-ethernet.cloned-mac-address.

Also we need a way to generate a random MAC here is a simple solution to create a completely random MAC address (Base source):

echo $RANDOM | md5sum | sed\
 's/^\(..\)\(..\)\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4:\5:\6/'

Final solution

Finally in your script use something like this:

mac=$(echo $RANDOM | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4:\5:\6/')
nmcli connection modify enp3s0 802-3-ethernet.cloned-mac-address $mac

There might be also a need to reload the connection:

nmcli connection down enp3s0
nmcli connection up enp3s0

You can put it in .profile or any other place you want.


Create random mac with valid OUI

If you don't want a completely random mac address then download this from GNU MAC Changer GitHub repository.

Then use this line to generate mac addresses:

shuf -n1 OUI.list | cut -f1-3 -d' ' | tr ' ' ':' | xargs -I company echo\
 company:`echo $RANDOM|md5sum|sed 's/^\(..\)\(..\)\(..\).*$/\1:\2:\3/'`
  • shuf -n1 OUI.list: selects a random line from that file.
  • cut -f1-3 -d' ' cuts the three necessary fields
  • tr ' ' ':' transforms it to a form we want
  • xargs ... creates the other three random part and concatenates the result.