Skip to content

Instantly share code, notes, and snippets.

@strayer
Created October 28, 2013 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save strayer/7198867 to your computer and use it in GitHub Desktop.
Save strayer/7198867 to your computer and use it in GitHub Desktop.
Command line script for retrieving the current external IP via the FritzBox UPnP API (requirements: requests, lxml)
#!/usr/bin/env python3
import requests
import sys
from lxml import etree
from io import StringIO
if len(sys.argv) < 2 or sys.argv[1] == "-h" or sys.argv[1] == "--help":
print("Usage: {} <fritzbox hostname>".format(__file__))
sys.exit(0)
fritzbox_host = sys.argv[1]
fritzbox_url = "http://{}:49000/upnp/control/WANIPConn1".format(fritzbox_host)
headers = {
'Content-Type': 'text/xml; charset="utf-8"',
'SoapAction': 'urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress'
}
post_payload = """<?xml version='1.0' encoding='utf-8'?> <s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'> <s:Body> <u:GetExternalIPAddress xmlns:u=urn:schemas-upnp-org:service:WANIPConnection:1 /> </s:Body> </s:Envelope>"""
try:
r = requests.post(fritzbox_url, data=post_payload, headers=headers)
except Exception as e:
print("Error: Could not call FritzBox API ({})".format(e), file=sys.stderr)
sys.exit(-1)
if r.status_code != 200:
# Lazy error message parsing
try:
tree = etree.parse(StringIO(r.text))
msg = tree.xpath('.//ns:errorDescription', namespaces={'ns': 'urn:schemas-upnp-org:control-1-0'})[0].text
print("Error: UPnP call failed ({})".format(msg), file=sys.stderr)
except Exception:
print("Error: UPnP call failed", file=sys.stderr)
sys.exit(-1)
try:
tree = etree.parse(StringIO(r.text))
ip = tree.xpath('.//NewExternalIPAddress')[0].text
print(ip)
except Exception as e:
print("Error: Could not read IP address from FritzBox response ({})".format(e), file=sys.stderr)
sys.exit(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment