Bash – Dynamic Public IP Address Monitor Script

image_pdfimage_print

This is a script I wrote to monitor my public IP address to see if it changes or not. It comes in very handy if you run a server on a dynamic IP address. It is setup to run in a daily cron job every morning. The script sends an email that lets me know if the IP address has changed or not, and also reports the current public IP address. Note that this script requires that curl is installed.

#!/bin/bash

#Script to report public IP address change
#By: Ronny L. Bull

TO="youremail@yourdomain.com"
FROM="alerts@yourdomain.com"

#The file that contains the current pubic IP
EXT_IP_FILE="/path/to/ipaddress"

#Get the current public IP from whatsmyip.com
CURRENT_IP=$(curl http://automation.whatismyip.com/n09230945.asp)

#Check file for previous IP address
if [ -f $EXT_IP_FILE ]; then
KNOWN_IP=$(cat $EXT_IP_FILE)
else
KNOWN_IP=
fi

#See if the IP has changed
if [ "$CURRENT_IP" != "$KNOWN_IP" ]; then
echo $CURRENT_IP > $EXT_IP_FILE

#If so send an alert
echo "Subject: The IP Address at home has changed
The IP address at home has been changed to $CURRENT_IP" | sendmail -f ${FROM} ${TO}

logger -t ipcheck -- IP changed to $CURRENT_IP
else

#If not just report that it stayed the same
echo "Subject: The IP Address at home is the same
The IP address at home stayed the same $CURRENT_IP" | sendmail -f ${FROM} ${TO}
logger -t ipcheck -- NO IP change
fi