DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Oliver has posted 3 posts at DZone. View Full User Profile

Get Router (AVM FritzBox [http://www.avm.de]) Connection Status Via UPNP

03.03.2009
| 7587 views |
  • submit to reddit
        From: Oliver Paulus, http://blog.code-project.org

This script can be used (e.g. with nagios [http://www.nagios.org]) to get router (AVM FritzBox [http://www.avm.de]) connection status via UPNP. 

Return codes:
 0 = Ok and connected
 1 = not connected
 2 = unknown error (communication problem, etc.)

import os, sys

import pycurl
import libxml2

class Response:
    def __init__(self):
        self.contents = ''
    def body_callback(self, buf):
        self.contents = self.contents + buf

# use your IP here!
url = "http://192.168.2.1:49000/upnp/control/WANIPConn1"
if len(sys.argv) > 1:
   url = sys.argv[1]

data = """
<?xml version="1.0"?> 
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" 
  s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> 
   <s:Body> 
      <u:GetStatusInfo xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1" /> 
   </s:Body> 
</s:Envelope>"""

r = Response()
c = pycurl.Curl()
try:
    try:
        c.setopt(pycurl.URL, url)
        c.setopt(pycurl.POST, 1)
        c.setopt(pycurl.POSTFIELDS, data)
        c.setopt(pycurl.INFILESIZE, len(data))
        c.setopt(pycurl.WRITEFUNCTION, r.body_callback)
        c.setopt(pycurl.CONNECTTIMEOUT, 30)
        c.setopt(pycurl.TIMEOUT, 300)
        c.setopt(pycurl.HTTPHEADER, ['SOAPACTION: "urn:schemas-upnp-org:service:WANIPConnection:1#GetStatusInfo"', 'CONTENT-TYPE: text/xml;', 'User-Agent: nagios'])
        c.perform()
    except:
        print "ERROR - HTTP request to UPNP server not possible"
        sys.exit(2)
finally:
    c.close()

exitcode = 2
try:
    try:
        doc = libxml2.parseDoc(r.contents)
        ctxt = doc.xpathNewContext()
        ctxt.xpathRegisterNs('s',"http://schemas.xmlsoap.org/soap/envelope/")
        ctxt.xpathRegisterNs('u',"urn:schemas-upnp-org:service:WANIPConnection:1")
        elements = ctxt.xpathEval('/s:Envelope/s:Body/u:GetStatusInfoResponse/NewConnectionStatus')
        state = elements[0].content
        elements = ctxt.xpathEval('/s:Envelope/s:Body/u:GetStatusInfoResponse/NewUptime')
        uptime = elements[0].content
        print "OK - %s: uptime: %ss" % (state, uptime)
        if state == "Connected":
            exitcode = 0
        else:
            exitcode = 1
    finally:
        doc.freeDoc()
except:
    print "ERROR - cannot parse UPNP response or response invalid"

sys.exit(exitcode)