Wednesday, May 13, 2009

Automated notification of updated of external IP

Updated 2013-03-16

Script stopped working due to changes in html2text this was resolved by adding curl as a dependency.

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.
Dependencies: curl, html2text and ssmtp.
Source formatted by formatmysourcecode.blogspot.com and available for download on github 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=youdirhere
# E-mail address, both from and to
ADDRESS=your@emailadress.here
# E-mail Subject
SUBJECT="New IP number"

# 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

    # Get current IP
    currentIP=`curl http://checkip.dyndns.org | html2text | 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
exit 0

2 comments:

  1. Cool idea! You might want to mention that users need to have html2text installed from their distributions repository. Also, getting error at Line 38 on the comparison of old IP vs new IP address.

    ReplyDelete
    Replies
    1. Hi Bill,

      Thanks for the heads up! I have already update my local copy of the script but forgot this old blogpost. It's updated and should be working now.

      Delete