Wednesday, May 13, 2009

Automated notification of updated of external IP

For my DSL line I get a dynamic IP address. On the inside it's quite easy to find out what the external IP is, but on the outside damn near impossible to find out what the IP might have changed to.
To get around that problem I wrote a little script that checks the external IP and sends me an e-mail if there has been any changes.

The script uses html2text and ssmtp.
Unfortunately blogger doesn't handle tab intendentions very well. But if your really want those identations, you can download the script here.



#!/bin/sh

# ipquery.sh
# IP checker and updater by Markus Ulfberg 2009-05-12

# Variables
# Path where ip.txt resides or will be created if it doesen't exist already
DIR=your_path_here
# E-mail address, both from and to
ADDRESS=your_email_address_here
# E-mail Subject
SUBJECT="New IP-number"
# update interval in minutes
UPDATE_INTERVAL=15

# Check for ip.txt and create if it doesn't exist.
if [ ! -s $DIR/ip.txt ]
then
# Create ip.txt
echo "ip.txt doesn't exist. Creating ip.txt ..."
echo "0.0.0.0" > $DIR/ip.txt
else
echo "ip.txt exists. Continuing ..."
fi

# Loop
while [ 1 ]
do
# Get current IP
currentIP=`html2text http://checkip.dyndns.org | grep Current | awk '{print$4}'`
echo "Current IP: $IP"

# Read old IP from file
oldIP=`cat $DIR/ip.txt`
echo "Old IP: $oldIP"

# Compare current and old IP
if [ $oldIP != $currentIP ]
then
echo "IP has changed to: $currentIP"
# Write new IP to ip.txt
echo $currentIP > $DIR/ip.txt
# Set e-mail content to new IP
CONTENT=$currentIP
# Send the e-mail notification
echo -e "FROM:$ADDRESS\nTO:$ADDRESS\nSUBJECT:$SUBJECT\nContent-type:text/plain\n$CONTENT\n" | `/usr/sbin/ssmtp $ADDRESS`
else
echo "IP is still: $currentIP"
fi
# Wait before running the loop again
sleep "$UPDATE_INTERVAL"m
done

0 comments:

Post a Comment