Platinum Partner

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

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 = """
 
 
    
       
    
"""

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)
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}