Skip to content

Instantly share code, notes, and snippets.

@xtex404
Last active June 3, 2016 06:18
Show Gist options
  • Select an option

  • Save xtex404/e4b70ec53c88a38d9f15 to your computer and use it in GitHub Desktop.

Select an option

Save xtex404/e4b70ec53c88a38d9f15 to your computer and use it in GitHub Desktop.
randomize_mac_address.sh
#!/bin/sh
#
# randomize the WAN mac address on a DD-WRT based router, save it to nvram
# then restart. this was a bit of a challenge since $RANDOM doesn't exist,
# and none of the standard GNU random utilities are installed by default.
#
# this isn't bash. it's like going back to 1978. ;)
#
# i'm sure this could be written to be more efficient. not really a huge
# concern, since this only runs once every few days, if that often.
#
# use full paths, since there's no guarantee our PATH will be valid or
# exist if this runs outside of a user shell
#
# put this in /jffs or in /opt if you've got memory backing. this reboots
# the router, so you're going to lose any changes made anywhere else on
# the file system.
#
randnum() {
/bin/grep -m1 -ao "[0-9]" /dev/urandom | /usr/bin/head -n1
}
get_octet() {
R1=-1
R2=-1
R3=-1
while [[ $R1 -lt 0 || $R1 -gt 2 ]]; do
R1=$( randnum 2 )
done
if [[ $R1 == 2 ]]; then
MAXR2=5
else
MAXR2=9
fi
while [[ $R2 -lt 0 || $R2 -gt $MAXR2 ]]; do
R2=$( randnum $MAXR2 )
done
if [[ $R1 == 2 && $R2 == 5 ]]; then
MAXR3=4
else
MAXR3=9
fi
while [[ $R3 -lt 0 || $R3 -gt $MAXR3 ]]; do
R3=$( randnum $MAXR3 )
done
if [[ $R1 != 0 ]]; then
OUT=$R1
fi
if [[ $R1 != 0 && $R2 != 0 ]]; then
OUT=${OUT}${R2}
fi
OUT=${OUT}$R3
/bin/echo -n $OUT
}
old_mac="$( /usr/sbin/nvram get def_hwaddr )"
O1=$( get_octet )
O2=$( get_octet )
O3=$( get_octet )
old_mac_prefix="$( /bin/echo $old_mac | /usr/bin/cut -d ":" -f 1-3 )"
new_mac=$( /usr/bin/printf "%s:%02X:%02X:%02X" $old_mac_prefix $O1 $O2 $O3 )
echo "###"
echo "###"
echo "### Changing WAN MAC to: $new_mac"
echo "###"
echo "###"
echo ""
echo "Ctrl-C within 10 seconds to abort..."
sleep 10
echo ""
echo "Setting new MAC and rebooting."
/usr/sbin/nvram set def_hwaddr=$new_mac
/usr/sbin/nvram commit
/bin/sync
/bin/sync
/bin/sync
echo "Bye... see you in 2 minutes"
/sbin/reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment