Python script to SMS and email on ip change

If like me you have an ISP that likes to regularly change your IP address and need to know when it changes and what the new IP is, then this is for you.

This script runs from cronjob and checks the current public IP address against the last known public address and if they are not the same, it will text and email the new IP address to you.

This script utilises a Custom Sms class which can be found here.

The IP log file must exist for this script to work.

#!/usr/bin/env python
#
# ipupdate.py
# Check public IP, on change send out sms and email notification
# http://linux-101.org
#
 
import string
import httplib
import smtplib
from sms import Sms
from email.Utils import formatdate
 
# Set some variables
smtpServer = "mailsrv.example.com"
smtpUser = "home-pc@example.com"
smtpPass = "home-pc-password"
fromAddress = "home-pc@example.com"
toAddress = ("recipient@example.net")
mobileNumber = "0123456789"
logFile = "/var/log/ip-log.log"
 
try:
    conn = httplib.HTTPConnection("ip.appspot.com")
    conn.request("GET", "/")
    r1 = conn.getresponse()
#    print r1.status, r1.reason
    Only run if we get 200 OK response code from server.
    if r1.status == 200:
        data1 = r1.read()
        straddr = data1.strip("\n")
        logfile = open(logFile,"r")
        lineList = logfile.readlines()
        oldip = lineList[-1]
        logfile.close()
        # If IP is unchanged, close and exit.
        if oldip.strip() == straddr:
            logfile.close()
            conn.close()
        else:
            # If new IP, first write to log, then send SMS, then send email
            logfile = open(logFile,"a")
            logfile.write(straddr + "\n")
            logfile.close()
            conn.close()
            sms = TextMessage(recipient=mobileNumber, message="New IP address is: \r" + straddr)
            sms.connectPhone()
            sms.sendMessage()
            sms.disconnectPhone()
            s = smtplib.SMTP(smtpServer)
            s.set_debuglevel(0)
            s.ehlo()
            s.starttls()
            s.ehlo()
            # Hash out below line if login is not needed
            s.login(smtpUser, smtpPass)
            emailDate = formatdate(localtime=True)
            emailMsg = """From: Home PC <home-pc@example.com>
Date: """ + emailDate + """
Subject: IP Address has changed.
 
New IP address is: """ + straddr + """
"""
            s.sendmail(fromAddress, toAddress, emailMsg)
            s.close()
except:
    print "Exception raised! Something's not working."
Burtronix Banner W3C Banner