Bash Script to Set a New Random MAC Address

This script generates a new random MAC address using hexdump and sets it for a specified network USB interface. It requires the USB interface name as a parameter.
mail@pastecode.io avatar
unknown
sh
16 days ago
777 B
1
Indexable
Never
#!/bin/bash
Get_New_Hex () {
    HexVal=$( hexdump -vn$1 -e'1/1 "%02X"' /dev/urandom )
}
NewMACAddress="00:00:00:00:00:00"
clear
if [ "$#" -eq 0 ]
then
  Result=$(ifconfig -a)
  echo "$Result" | awk '/'$NewMACAddress'/{print previous_line}{previous_line=$0}'
  echo "$Result" | grep -zoP '.*(?='$NewMACAddress').*'
  echo; echo
  echo "'update_usb_mac.sh <param>': Get the interface name if detected and"
  echo "                             input it as a parameter next time."
  exit 1
fi
Get_New_Hex 1; NewMACAddress="$HexVal"
n=5
for (( i=1 ; i<=$n ; i++ )); 
do
    Get_New_Hex 1; NewMACAddress="$NewMACAddress:$HexVal"
done
echo; echo "Generated New MAC Address -> $NewMACAddress"; echo
sudo ifconfig $1 down
sudo ifconfig -v $1 hw ether $NewMACAddress
sudo ifconfig $1 up
Leave a Comment