Email notification if IP is changed with Python and cron

This Python script retrieves computer’s external IP address (using internet.yandex.ru) and emails message with new IP if IP has been changed since last check. BeautifulSoup module is needed, so install it if you have no installed version:

sudo pip install beautifulsoup

Script:

#!/usr/bin/env python

from BeautifulSoup import BeautifulSoup
import urllib2
import re
import smtplib
from email.mime.text import MIMEText

logFile = '/var/log/ippywatchdog.log'

request = urllib2.urlopen('http://internet.yandex.ru')

soup = BeautifulSoup(request)
yandexIpResponse = soup.find('div', {'class': 'b-info__item b-info__item_type_ip'})
ip=re.search('[0-9]+.[0-9]+.[0-9]+.[0-9]+', str(yandexIpResponse)).group(0)

prevIp = ip

try:
    with open(logFile,'r') as log:
        prevIp = log.readline()
        log.close()
except IOError:
    pass

if (ip != prevIp):
	for recipient in ['<recipient0>', '<recipient1>']:
	    msg = MIMEText('New IP address of Server is ' + ip)
	    msg['Subject'] = 'IP address of Server changed'
	    msg['From'] = '<email>'

	    server = smtplib.SMTP('smtp.yandex.ru', 587)
	    server.ehlo()
	    server.starttls()
	    server.ehlo()
	    server.login(msg['From'], '<email_password>')

	    msg['To'] = recipient
	    server.sendmail(msg['From'], msg['To'], msg.as_string())
	    server.quit()

with open(logFile, 'w') as log:
    log.write(ip)
    log.close()

Replace <recipient0> and <recipient1> with emails which you want to receive warnings about IP change. You can add more recipients or leave the only one. Replace <email> and <email_password> with real email account and password (you need real account at ya.ru or similar email provider). SMTP server in the following code is configured for yandex mail.

Now place script to /opt/ippywhatchdog.py, make it executable, add to cron.

sudo -s
mv ippywhatchdog.py /opt/
chmod +x /opt/ippywhatchdog.py
crontab -e

crontab -e will open text editor with cron configuration. Add the following string to execute script every 5 minutes:

*/5 * * * * /opt/ippywatchdog.py