Email notification if IP is changed with Python and cron

2013-09-09
#python #howto #ip #cron #server

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

1sudo pip install beautifulsoup

Script:

 1#!/usr/bin/env python
 2
 3from BeautifulSoup import BeautifulSoup
 4import urllib2
 5import re
 6import smtplib
 7from email.mime.text import MIMEText
 8
 9logFile = '/var/log/ippywatchdog.log'
10
11request = urllib2.urlopen('https://internet.yandex.ru')
12
13soup = BeautifulSoup(request)
14yandexIpResponse = soup.find('div', {'class': 'b-info__item b-info__item_type_ip'})
15ip=re.search('[0-9]+.[0-9]+.[0-9]+.[0-9]+', str(yandexIpResponse)).group(0)
16
17prevIp = ip
18
19try:
20    with open(logFile,'r') as log:
21        prevIp = log.readline()
22        log.close()
23except IOError:
24    pass
25
26if (ip != prevIp):
27	for recipient in ['<recipient0>', '<recipient1>']:
28	    msg = MIMEText('New IP address of Server is ' + ip)
29	    msg['Subject'] = 'IP address of Server changed'
30	    msg['From'] = '<email>'
31
32	    server = smtplib.SMTP('smtp.yandex.ru', 587)
33	    server.ehlo()
34	    server.starttls()
35	    server.ehlo()
36	    server.login(msg['From'], '<email_password>')
37
38	    msg['To'] = recipient
39	    server.sendmail(msg['From'], msg['To'], msg.as_string())
40	    server.quit()
41
42with open(logFile, 'w') as log:
43    log.write(ip)
44    log.close()

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

Now place the script at /opt/ippywatchdog.py, make it executable, and add it to cron.

1sudo -s
2mv ippywatchdog.py /opt/
3chmod +x /opt/ippywatchdog.py
4crontab -e

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

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