November 29th, 2012, 09:27 AM
Script to Notify of Public IP Change
I manage a Linux Ubuntu 12.04 LTS server for a local police department. They have cable internet, and unsure of whether or not their ISP provided them with a static or dynamic IP address, I wrote a perl script to notify me if the IP address should ever change (since I manage the server remotely).
I only have 1 problem with this scripts. Sometimes, it seems to fetch a "blank" when trying to resolve the IP. It sees the "blank" address as new, so it will then send me an e-mail saying the address has changed. Then an hour later (when the cronjob goes off every hour on the hour), it will fetch the correct IP addy, and then notify again of the "new change." If I had to guess, it's during the actual resolving of the IP address and fetching that information that it seems to get this null IP.
I've pasted my code below for review. What do you all think?
#! /usr/bin/perl -w
# FETCH THE PUBLIC IP ADDRESS
$ip = `wget http://automation.whatismyip.com/n09230945.asp -O - -q ; echo`;
# OPEN FILE THAT CONTAINS THE IP ADDRESS
# AS OF THE LAST TIME THE SCRIPT WAS RAN
open FILE, "<", "/root/scripts/currentIP" or die $!;
$currentIP = <FILE>;
# COMPARE THE OLD IP AND THE FETCHED IP
# FOR DIFFERENCES
if ($currentIP ne $ip)
#IP HAS CHANGED; EMAIL ADMIN THE NEW IP
#AND THEN CHANGE THE IP RECORD FILE
open FILE, ">", "/root/scripts/currentIP" or die $!;
print FILE $ip;
# E-MAIL SUB ROUTINE
# (I HAVE EXIM4 SETUP TO FORWARD TO GOOGLE
# SMARTHOST SO I CAN RECEIVE MAIL AS ROOT)
my $headers = "PD IP Change\nFrom: ipUpdater Script\nUser-Agent: Heirloom mailx 12.5 6/20/10\nMIME-Version: 1.0\nContent-Type: text/plain; charset=us-ascii\nContent-Transfer-Encoding: 7bit\n";
my $to = "root";
my $body = "The public IP address for the BPDServer has changed.\n\nNew IP: $ip\nOld IP: $currentIP\n.";
system("echo \"$body\" | mail -s \"$headers\" \"$to\"");
November 29th, 2012, 01:35 PM
The simple and best solution for that problem is to call the ISP and ask them what they are providing.
Before I comment on your code I must ask, if they are providing a dynamic address, which would be wrong in this case, have you thought of using DDNS and a hostname (URL)?
November 29th, 2012, 02:17 PM
November 29th, 2012, 03:21 PM
I did take DDNS into consideration, but didn't want to do the extra set-up work (lazy in that way), and didn't want to pay for a third-party service. Also, since I'm still new to Perl, I wanted to challenge myself with coming up with my own solution.
Originally Posted by FishMonger
@spacebar208: Thanks for those links! I'll give them a more thorough reading when I have some time later.
December 2nd, 2012, 08:13 AM
Static or Dynamic IP
It depends upon the company you get the services of. There are many good and reliable sites which offer static and dynamic IPs at very reasonable pricing such as proxy rental. Their trial is free. I have got their support.