Skip to content

Instantly share code, notes, and snippets.

@luuksommers
Created October 27, 2013 13:12
Show Gist options
  • Save luuksommers/7181864 to your computer and use it in GitHub Desktop.
Save luuksommers/7181864 to your computer and use it in GitHub Desktop.
Monitor IP changes with Python and Pushover
import re
import os
import uuid
import json
import socket
import urllib, urllib2
import time
def get_current_ip():
req = urllib2.Request('http://checkip.dyndns.org/')
response = urllib2.urlopen(req)
the_page = response.read()
p = re.compile(r'(?P >ip<(?:[0-9]{1,3}\.){3}[0-9]{1,3})')
m = p.search(the_page)
return m.group('ip')
# load settings
current_ip = get_current_ip()
uid = ''
computer_name = ''
last_ip = ''
if(os.path.exists('oswos.settings')):
with open('oswos.settings', 'r') as f:
content = f.read()
decoded = json.loads(content)
uid = decoded.get('guid')
computer_name = decoded.get('computer_name')
last_ip = decoded.get('last_ip')
else:
uid = str(uuid.uuid1())
computer_name = socket.gethostname()
data = { 'guid': uid, 'computer_name': computer_name, 'last_ip': current_ip }
with open('oswos.settings', 'w') as f:
json.dump(data, f)
print 'uid : {0}'.format(uid)
print 'computer_name: {0}'.format(computer_name)
print 'last_ip : {0}'.format(last_ip)
print 'current ip : {0}'.format(current_ip)
if(current_ip != last_ip):
API_URL = "https://api.pushover.net/1/messages.json"
API_KEY = "api-key-here"
curUrl = API_URL
data = urllib.urlencode({
'token': API_KEY,
'title': 'Oswos Notification',
'user': 'user-key-here',
'message': 'IP Changed from {0} to {1}'.format(last_ip,current_ip).encode('utf-8'),
'timestamp': int(time.time())
})
req = urllib2.Request(curUrl)
handle = urllib2.urlopen(req, data)
handle.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment