Normalize MAC address for DHCP reservations
So part of what I am doing at my current job is helping one of the Unix admins with DNS and DHCP. For the DHCP portion to setup the reservations we need the MAC addy in a certain format, of which the people requesting never seem to get consistently right, so I wrote a small shell script (it’s still rough) that will normalize the MAC address for what we need (colon separated, alpha characters lower case).
[Edit: the below only works on FreeBSD and Linux, for Solaris swap the awk '{print tolower($0)}' with tr '[:upper:]‘ ‘[:lower:]‘ <- or you could just do that for all of them as well).
#!/usr/bin/env sh mac="$1" #check to see if input is empty if [ ! -n "$mac" ] then echo "Please enter a MAC address." exit else # echo the input, strip out dot(.), strip out colon(:), strip out dash(-) # add colon(:) every two chars, remove last colon(:) # awk to lowercase characters [EDIT: updated the sed for . seps and escape] echo $mac | sed -e 's/\.//g' -e 's/\://g' -e 's/\-//g' -e 's/../&:/g' -e 's/:$//g' \ | awk '{print tolower($0)}' fi
Some of the standard formats we see are:
1A:BC:35:57:33:08
1A-BC-35-57:33:08
1ABC35573308
1abc35573308
1a.bc.35.57.33.08
1A.BC.35.57.33.08
The script will take all of these and make them look like: 1a:bc:35:57:33:08.
Here is the breakdown for those that are curious:
1. if [ ! -n "$mac" ] checks to make sure first input variable is not empty.
2. echo $mac outputs the first argument (does not do any input validation)
3. The sed is in five parts:
[Edited to escape the sequences, just in case they should have special meaning]
a. 's/\.//g' strips out the period should it be in that format
b. 's/\://g' strips out the colons should they be there (to avoid extra colons)
c. 's/\-//g' strips out the dashes should they be in that format
d. 's/../&:/g' every two characters append a colon
e. 's/:$//g' remove the last trailing colon
4. awk ‘{print tolower($0)}’ make all of the upper case alpha chars lower case to match our format needs.
4a. tr ‘[:upper:]‘ ‘[:lower:]‘ for Solaris (yes I know tr ‘[A-Z]‘ ‘[a-z]‘ will work as well, but this is easier to read IMHO)
This will work on a file full of MAC addresses, just throw it in a for loop (this is if you name the file macnorm.sh):
for i in `cat filename`; do ./macnorm.sh $i; done
Again it is important to realize that there is no checking of the input, so if you did it over /etc/passwd it would add a colon (:) every two characters. Hope this helps.
-Scott.

August 16th, 2011 at 17:32:40
[...] MAC address with Python In an earlier post, Scott did this in a simple shell script. I was curious if I could do it in Python since I am [...]