Context
My Internet Service Provider changes my externally-visible IP Address from time to time without notice. I am having issues with the ISP’s service and I decided to keep a watch on my Internet connectivity unsing external monitoring services. Since I donlt have a static IP address visible to the Internet I needed to work out a way to make sure that the monitoring configuration gets to use the current IP address of my monitoring endpoint despite the ISP changing the IP address. I use Dynamic DNS service. More on this in a subsequent article.
In this article I present a simple Unix script which keeps track of my changing external IP addresses so that I can see what they were at different points in time and when they were changed. This script attempts to resolve the domain name of the host to its I address as means of obtaining the IP address which is visible form the Internet.
Script
I have a pfSense firewall (https://www.pfsense.org/), which is based on the FreeBSD OS. The script being discussed runs on this firewall.
The purpose of the script is to resolve the externally-visible host name of my externally-visible host, compare it to the last IP address that was resolved and, if they are different, update the last resolved IP Address and log a change to the system log and the private log created for the purpose.
Set prerequisites (manually create myip_last.log for the first time):
mkdir -pv ~/ipaddresses
# seed for the first time myip=$(nslookup somehostname.dynu.net 208.67.222.222 | grep Address | tail -n 1 | cut -c10-) echo "$(date -jR) - ${myip}" > ~/ipaddresses/myip_last.log
Create the script:
> ~/log_ip_change.sh # create empoty script file chmod u+x ~/log_ip_change.sh # set permissions to allow script execution cat <<-'EODECK' > ~/log_ip_change.sh # create the script via a HERE-document #!/bin/sh myip=$(nslookup somehostname.dynu.net 208.67.222.222 | grep Address | tail -n 1 | cut -c10-) olip=$(cat ~/ipaddresses/myip_last.log|cut -d'-' -f2|tr -d ' ') if [ $myip != $olip ]; then echo "$(date -jR) - ${myip}" > ~/ipaddresses/myip_last.log cat ~/ipaddresses/myip_last.log >> ~/ipaddresses/myip.log logger -p user.crit "IP Address change: $(cat ~/ipaddresses/myip_last.log)" fi EODECK
Add this script to crontab and run it every minute
crontab -eAdd the following line
*/1 * * * * /root/log_ip_change.sh 2>/root/ipaddresses/log_ip_change.err
Give it 1 minute and see what the logs say
cat ~/ipaddresses/myip_last.log
cat ~/ipaddresses/myip.log
Summary
In this article I present a script which watches and records my externally-visible IP addresses, as changed bymy ISP form time to time, by resolving my externally-visible host name to the IP address – call me curious 🙂