Saturday, May 11, 2013

Monitor your Server IP with Python and Pushover

Since I'm running my own web / plex server, I want to be notified when my public IP changes. This is super-easy using python and pushover.

The base of the application is really simple; fetch the IP from and check if it's the same as the last time you've runned. If it has changed, send a message with pushover to your mobile phone.

I use crontab every 5 minutes to validate the IP.

Here's the script:

import re
import os
import uuid
import json
import socket
import urllib, urllib2
import time

def get_current_ip():
    req = urllib2.Request('')
    response = urllib2.urlopen(req)
    the_page =

    p = re.compile(r'(?P >ip<(?:[0-9]{1,3}\.){3}[0-9]{1,3})')
    m =

# load settings
current_ip = get_current_ip()
uid = ''
computer_name = ''
last_ip = ''

    with open('/srv/crontab/oswos.settings', 'r') as f:
        content =
        decoded = json.loads(content)
        uid = decoded.get('guid')
        computer_name = decoded.get('computer_name')
        last_ip = decoded.get('last_ip')
    uid = str(uuid.uuid1())
    computer_name = socket.gethostname()

data = { 'guid': uid, 'computer_name': computer_name, 'last_ip': current_ip }
with open('/srv/crontab/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 = ""
    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)

You see how easy it is to connect to Pushover? Building your own good working Android application is hard, so why not use the tools which are already there!

Just let me know if you have any tips / suggestions to extend this further.


No comments:

Post a Comment