Skip to content

Instantly share code, notes, and snippets.

@mattvh
Last active November 12, 2021 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattvh/1e3194b8b457e7b3f49832ee30a943b6 to your computer and use it in GitHub Desktop.
Save mattvh/1e3194b8b457e7b3f49832ee30a943b6 to your computer and use it in GitHub Desktop.
# Raspberry Pi Pushover IP Notifier
# by Matt Harzewski (2021)
# License: MIT
#
# On system boot, this script checks to see if
# the IP address has changed, and sends a
# Pushover notification if it is different.
#
# Set the user and application tokens with your
# own from Pushover.net, and add the script to
# the crontab: @reboot python3 path/to/ipnotify.py
from urllib import request, parse
from datetime import datetime, date
import socket, os.path, subprocess
def push(title, msg):
params = {
"token": "PUSHOVER_APP_TOKEN",
"user": "PUSHOVER_USER_TOKEN",
"title": title,
"message": msg
}
req = request.Request(
"https://api.pushover.net/1/messages.json",
data=parse.urlencode(params).encode()
)
res = request.urlopen(req)
def getIp():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = None
try:
sock.connect(('8.8.8.8', 1))
ip = sock.getsockname()[0]
except Exception:
sock.close()
sock.close()
return ip
def storeIp(ip):
with open(os.path.expanduser('~/.ipnotify'), "w+") as f:
f.write(f"{ip}|{getUptime()}")
def getStoredIp():
ip = None
when = None
with open(os.path.expanduser('~/.ipnotify'), "r") as f:
data = f.read()
data = data.split('|')
ip = data[0]
when = data[1]
return ip, when
def getUptime():
return subprocess.getoutput('uptime -s')
if __name__ == '__main__':
current = getIp();
today = datetime.combine(date.today(), datetime.min.time())
if os.path.exists(os.path.expanduser('~/.ipnotify')):
prev, when = getStoredIp()
dt = datetime.strptime(when.strip(), "%Y-%m-%d %H:%M:%S")
if current != prev or dt < today:
push("Current IP", current)
storeIp(current)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment