A simple program written in Python for Raspberry Pi although it should work on other Linux distros. It looks up the public ip address and compares it with what it had last time. If it has changed then email the news and replace the stored ip with the new address. The email includes a link to look up the new address on Spamhaus Zen to determine if it is on a blacklist and what to do if it is.
ipmonitor.py
#!/usr/bin/env python3
# ipmonitor - David Brewerton 2023
# v 20231130.0915
# ____________________________________
import configparser, os, sys, re
import time, socket, imaplib, traceback, datetime
from urllib.request import urlopen
from smtplib import SMTP_SSL, SMTP_SSL_PORT
from email.utils import formatdate
from email.message import EmailMessage
def get_config_file_path():
# use the configparser to bring in the mailserver credentials
if "--help" in sys.argv or "-h" in sys.argv:
display_help_text()
if "--config-path" in sys.argv and len(sys.argv) >= 3:
global config_file_path
config_file_path = sys.argv[2]
if not os.path.isfile(config_file_path):
print("Configuration file not found. Expected it at '" + config_file_path + "'.")
exit(-1)
def display_help_text():
print("Options:")
print("\t--help: Display this help information")
print("\t--config-path : "
"Override path to config file (defaults to same directory as the script is)")
exit(0)
def sendemail():
# Assemble the email using email.message.EmailMessage
from_email = myname + ' <' + username + '>'
to_emails = myname + ' <' + username + '>'
email_message = EmailMessage()
email_message.add_header('To', to_emails)
email_message.add_header('From', from_email)
email_message.add_header('Subject', 'IP is now '+curr_IP_strip+' which has changed')
email_message.add_header('X-Priority', '1')
email_message.add_header('Date', formatdate(localtime=True))
email_message.set_content(sendbody)
# Connect, authenticate, and send mail
smtp_server = SMTP_SSL(mailserver, port=SMTP_SSL_PORT)
smtp_server.set_debuglevel(0) # Show SMTP server interactions = 1
smtp_server.login(username, password)
# print(time.strftime("%a %H:%M:%S"),'REPLY:', msg.uid, '"',from_email, ',', to_emails, ',', email_message.as_bytes())
smtp_server.sendmail(from_email, to_emails, email_message.as_bytes())
# Disconnect
smtp_server.quit()
# *** RUN ROUTINE ***
# Initialise and read in config
config_file_path = "ipmonitor.ini"
get_config_file_path()
# this is so the credentials config can be passed on the command line if required
config_file = configparser.ConfigParser()
config_file.read(config_file_path, encoding="UTF-8")
myname = (config_file["login credentials"]["mailserver.myname"])
username = (config_file["login credentials"]["mailserver.username"])
password = (config_file["login credentials"]["mailserver.password"])
mailserver = (config_file["login credentials"]["mailserver.server"])
# Open up the url, then read the content, and take away to IP address
url = "http://ip.42.pl/raw"
request = urlopen(url,timeout=15).read().decode("utf-8")
# Extract the IP address only
curr_IP = str(re.findall("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", request))
# Open last_ip and extract the contents
with open("/home/sq/ipmonitor.txt", "rt") as last_ip:
last_ip = last_ip.read() # Read the text file
# Check to see if our IP address has changed
if last_ip == curr_IP:
print ("IP address has not changed and is",curr_IP)
else:
sendbody = "New IP address is "
sendbody += curr_IP
curr_IP_strip = curr_IP.strip("[]'")
print(sendbody, end="")
with open("/home/sq/ipmonitor.txt", "wt") as last_ip:
last_ip.write(curr_IP)
print (" which has been stored",end="")
sendbody += "\n\nCheck to see if this ip is on Spamhaus Zen's blacklist:-"
sendbody += "\nhttps://check.spamhaus.org/listed/?searchterm=" + curr_IP_strip
sendbody += "\n\nThe Policy Blocklist (PBL) can be ignored but if there are 2 listings "
sendbody += "and the other is the CSS Blocklist it is worth requesting it to be cleared. "
sendbody += "You should advise them that this new address has just been inherited from your ISP."
sendbody += "\n\nYou will have to verify the email that they send you!"
sendbody += "\n\nKind regards\n\nYour ip monitor"
sendemail()
print (" and emailed")
Initialise ipmonitor.txt which holds the last ip address
[111.111.111.111]
Create the credentials config file which we will call ipmonitor.ini but this can be passed on the command line with –config-path which allows you to call it anything and stored it anywhere for some safety.
[login credentials] mailserver.username = your-email-address@thingy.com mailserver.password = your-email-password mailserver.server = your-IMAP-and-SMTP-server-url mailserver.myname = Your Normal Name
You will probably want to run this regularly in CRON so open crontab…
crontab -e
Add something like the following at the bottom of the contents to run every 30 minutes. This will write the log to ipmonitor.log
*/30 * * * * /usr/bin/python3 -u /home/pi/ipmonitor.py --config-path /home/pi/ipmonitor.ini 1>ipmonitor.log 2>&1 &