This is my lean and effective way to monitor your public IP address with Python, specifically Python3. The script – code and GitHub link below – runs on a continuous loop, which I covered in a previous post: here.
NOTE: this code is reliant on the
dig system command – so this essentially only work on a unix based system. I was running this on a Debian install.
import os import subprocess import re import time print("start monitor vpn monitor check") expected_IP = "0.0.0.0" # ENTER YOUR EXPECTED PUBLIC IPv4 ADDRESS HERE current_IP = subprocess.check_output("dig +short myip.opendns.com @resolver1.opendns.com", shell=True) try: while True: if expected_IP in str(current_IP): print("IPs Match - Things are normal") else: print("Current IP: " + str(current_IP) + "\nIP NOT AS EXPECTED!") #Code to complete actions called here time.sleep(60) # Change this timer to reduce/increase time between checks (seconds) except KeyboardInterrupt: print("\nHard Exit Initiated. Goodbye!")
There are a number of use cases for this code, mine was checking if my computer is still connected to a VPN. Monitor my public IP address meant that I could tell if the VPN had disconnected.
The only thing that was changed here from the current repository code is the print statements – the output just matches the context of the code’s use.
More python snippets
Here are some links to some of my other python code samples: