determine Mac location by IP address

One of the challenges that I face as a Mac engineer managing multiple offices around the world is writing an automation script to be compatible with each office, since I certainly don’t want to write 7 scripts, manage 7 scripts, and maintain 7 scripts (we have 7 locations). I’ve written a short piece of code that I put at the beginning of almost all of my scripts to set a few variables that will be used throughout the rest of the script; things like local server name and computer name prefix (varies by location).

NETADD=`ifconfig en0 | grep "inet " | grep -v 127.0.0.1 | cut -d\  -f2 | awk '{print substr($1,1,6)}'`
	case $NETADD in
	"10.227")
		Srvr="10.227.x.xServer"
                NamePrefix="SHAM"
		;;
	"10.209")
		Srvr="10.209.x.xServer"
                NamePrefix="CHIM"
		;;
	"10.201")
		Srvr="10.201.x.xServer"
                NamePrefix="FAIM"
		;;
	"10.215")
		Srvr="10.215.x.xServer"
                NamePrefix="CANM"
		;;
	"10.204")
		Srvr="10.204.x.xServer"
                NamePrefix="AFTM"
		;;
	"10.203")
		Srvr="10.203.x.xServer"
                NamePrefix="RIPM"
		;;
	*)
		Srvr="10.104.x.xServer"
                NamePrefix="CLEM"
		;;
	esac

“ifconfig en0”  gets the en0 network port configuration information. All of my company’s scripts and automation require the client’s ethernet port (en0) to be plugged in. While wireless works for general internet browsing and filesharing functions, we do not push software or configurations over the air.

Office locations are determined by the first two octets of a client’s IP address, so after piping the ifconfig en0’s output through a series of greps, we have to awk it to print the first 6 characters of the IP address. Capture this final string into a variable, and use a case statement to compare it to all known satellite office IP segments. From there, set name and local server variables accordingly.

This code segment has proven absolutely invaluable as the Mac workstations in the company have made their way into more and more satellite office.


About this entry