Python script: Wait for a site to come up and notify me

For the last weeks, i’ve been working a lot with different servers, which take longer and longer to deploy new application bundles. Mostly i know that the deployment is complete when the website or the webservices of that application are up and return a successful status code (not 404).
Another use case is when trying to access a remote website which is temporarily down, but you want to be notified immediately when it comes up again.

Since i don’t want to sit in front of my browser hitting F5 again and again (especially if it takes some minutes), i found it nice to watch the HTTP Server with a little script, which can run in background and send a little OS notification when the Site or Webservice is up again.

I’ll share it and hope anyone also has a use for this. For the notifications, you need the OS-independent notification library pynotify. If you are running Debian/Ubuntu, get it with apt-get install python-notify

#!/usr/bin/python
# Partly "borrowed" from:
# http://code.activestate.com/recipes/267197-urllib2-for-actions-depending-on-http-response-cod/
import urllib2
import pynotify
import time
import sys
from urllib2 import Request, urlopen, URLError, HTTPError

url = sys.argv[1]

print "Waiting for Site " + url + " to come up"

while True:
  try:
    urllib2.urlopen(url)
  except urllib2.HTTPError, e:
    if e.code == 401:
      print 'not authorized'
    elif e.code == 404:
      print 'not found'
    elif e.code == 503:
      print 'service unavailable'
    else:
      print 'unknown error: '
    time.sleep(3)
  else:
    print 'success'
    if pynotify.init("HTTP Monitor"):
      title_string = "HTTP Monitor"
      author_string = "Site " + url + " is available"
      n = pynotify.Notification(title_string, author_string, "emblem-shared")
      n.set_timeout(0)
      n.show()
      print author_string
      break

How the script is called:

python ~/tools/watchsite.py http://192.168.178.152:8080/UserService/UserServiceWSService?wsdl

Which looks like this:

Waiting for Site http://192.168.178.152:8080/UserService/UserServiceWSService?wsdl to come up....

And gives this nice notification (on Gnome) when the Server/Site/Service is up:

This entry was posted in General and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>