Saturday, December 19, 2015

Get your Synology NAS to notify you when your IP changes

I have a residential internet service. That means I never know when my IP address is going to change. But that is ok because I use DDNS Updater 2 in order to automatically update the DNS for my domain with the IP address of my Synology NAS when it changes. But the problem with that is DNS updates do not immediately propagate to every DNS server on the internet. It could take up to 24 hours until your domain is finally updated with the new IP.


So what I need is a script to notify me when my IP changes which I can use instead until my domain works again. I mostly need this for VPN. And off I went to write such a script:

#!/bin/sh                                                                              
ip_current=`curl -silent -L http://checkip.amazonaws.com|tail -n 1`

while :
do
    # Grab IP                                                                                                              
    ip=`curl -silent -L http://checkip.amazonaws.com|tail -n 1`
    # Compare IP                                                                                                           
    if [ "$ip" != "$ip_current" ]; then
        # Notify new IP                                                                                                    
        synodsmnotify admin "IP has changed" "New IP is $ip"
        # Set as current IP                                                                                                
        ip_current=$ip
    fi

    # Wait 20 minutes                                                                                                      
    `sleep 1200`
done

It is a pretty simple script. It will grab your current IP, and then in an infinite loop keep checking to see if it changes. If it did change, it will send a notification to admin. Then it will wait 20 minutes (1200 seconds) and check again. Since I am using Pushbullet with Synology, I get notified immediately. Having it email instead of notify would of been nice, but it would of involved more work to setup and ipkg to install a third-party program.

I called this script ip_notify.sh and placed it in /opt/local/bin. In order to get it to automatically run on boot, I put the following command in /etc/rc.local:

/bin/sh /opt/local/bin/ip_notify.sh

And that was it. Make sure the files are executable (chmod +x file_name).



No comments:

Post a Comment