Home » Computer » Automatically detect network and adapt /etc/hosts

Automatically detect network and adapt /etc/hosts

Here is a little bash script that allows you to detect a change in the wireless network connection of a Mac (using OS X 10.9.1 Mavericks). You may run it in the background or regularly using cron (then remove the while true loop).

#!/bin/bash
hosts_culan="/etc/hosts_CuLAN"
hosts_else="/etc/hosts_else"

while true; do
	ssid=`/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep " SSID" | awk '{print $2}'`

	if [[ -z "$ssid" ]]; then ssid="none"; fi

	echo "current WLAN ssid is $ssid"

	if [[ $ssid == "CuLAN" ]]; then
		echo "ssid is CuLAN"
		# check
		if [[ -f $hosts_culan ]]; then
			mv /etc/hosts $hosts_else
			mv $hosts_culan /etc/hosts
			echo "changed /etc/hosts to CuLAN"
		fi
	else
		echo "ssid is not CuLAN"
		if [[ -f $hosts_else ]]; then
			mv /etc/hosts $hosts_culan
			mv $hosts_else /etc/hosts
			echo "changed /etc/hosts to non-CuLAN network"
		fi
	fi
	echo "script done"
	sleep 10
done

I am currently moving my social media presence from Twitter to Mastodon

My Tweets