diff --git a/Changelog.md b/Changelog.md index e68292a..c2b969a 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,15 @@ # Changelog +## 7.25.0 +*2021-03-26* + +- Support for FritzOS!7.25 including log in via username password + +## 7.0.0 +*2018-09-11* + +- Support for FritzOS!7.00 + ## 6.83.2 *2017-09-05* diff --git a/README.md b/README.md index dc0fcfc..2c3e421 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # fritzbox-munin -A collection of munin plugins to monitor your AVM FRITZ!Box router. The scripts have been developed using a [FRITZ!Box 7590](http://geni.us/OO2c7S)(Amazon link) running FRITZ!OS 7.00. +A collection of munin plugins to monitor your AVM FRITZ!Box router. The scripts have been developed using a [FRITZ!Box 7590](http://geni.us/OO2c7S)(Amazon link) running FRITZ!OS 7.25. If you are using the scripts on a different Fritz!Box model please let me know by @@ -15,11 +15,13 @@ If you are using the scripts on a different Fritz!Box model please let me know b - [FRITZ!Box 7390](http://geni.us/BlAP) - [FRITZ!Box 7430](http://geni.us/BlAP) - [FRITZ!Box 7490](http://geni.us/fTyoY) +- [FRITZ!Box 7530](https://geni.us/h8oqYd) +- [FRITZ!Box 7530 AX](https://geni.us/a4dS5) - [FRITZ!Box 7560](http://geni.us/6gPZNI) - [FRITZ!Box 7580](http://geni.us/yUYyQTE) - [FRITZ!Box 7590](http://geni.us/OO2c7S) - If you are still running Fritz!OS 6.30 check out the [releases section](https://github.com/Tafkas/fritzbox-munin/releases/tag/6.30.1). + If you are still running an older Fritz!OS version check out the [releases section](https://github.com/Tafkas/fritzbox-munin/releases/). ## Introduction @@ -41,32 +43,32 @@ If you are using the scripts on a different Fritz!Box model please let me know b ## fritzbox\_cpu\_usage - fritzbox\_cpu\_usage shows you the cpu usage (requires password) + fritzbox\_cpu\_usage shows you the cpu usage (requires username & password) ![http://i.imgur.com/A9uGvWP.png](http://i.imgur.com/A9uGvWP.png) ## fritzbox\_cpu\_temperature - fritzbox\_cpu\_temperature shows you the cpu temperature (requires password) + fritzbox\_cpu\_temperature shows you the cpu temperature (requires username & password) ![http://i.imgur.com/duHYhw6.png](http://i.imgur.com/duHYhw6.png) ## fritzbox\_memory\_usage - fritzbox\_memory\_usage shows you the memory usage (requires password) + fritzbox\_memory\_usage shows you the memory usage (requires username & password) ![http://i.imgur.com/WhxrINK.png](http://i.imgur.com/WhxrINK.png) ## fritzbox\_power\_consumption - fritzbox\_power\_consumption shows you the power consumption (requires password) + fritzbox\_power\_consumption shows you the power consumption (requires username & password) ![http://i.imgur.com/a7uQzn6.png](http://i.imgur.com/a7uQzn6.png) ## fritzbox\_uptime - fritzbox\_uptime shows you the uptime in days (requires password) (language dependant, see below). + fritzbox\_uptime shows you the uptime in days (requires username & password) (language dependant, see below). ![http://i.imgur.com/Jr8OibH.png](http://i.imgur.com/Jr8OibH.png) ## fritzbox\_wifi\_devices - fritzbox\_wifi\_devices shows you the number of connected wifi clients (requires password) (language dependant, see below). + fritzbox\_wifi\_devices shows you the number of connected wifi clients (requires username & password) (language dependant, see below). ![http://i.imgur.com/lqvK1b2.png](http://i.imgur.com/lqvK1b2.png) ## Installation & Configuration @@ -85,6 +87,7 @@ If you are using the scripts on a different Fritz!Box model please let me know b [fritzbox_*] env.fritzbox_ip + env.fritzbox_username env.fritzbox_password env.traffic_remove_max true # if you do not want the possible max values host_name fritzbox diff --git a/fritzbox_connection_uptime.py b/fritzbox_connection_uptime.py index 5742610..85ce0aa 100755 --- a/fritzbox_connection_uptime.py +++ b/fritzbox_connection_uptime.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_connection_uptime - A munin plugin for Linux to monitor AVM Fritzbox connection uptime Copyright (C) 2015 Christian Stade-Schuldt @@ -10,6 +10,12 @@ This plugin requires the fritzconnection plugin. To install it using pip: pip install fritzconnection This plugin supports the following munin configuration parameters: + + [fritzbox_*] + env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] + env.fritzbox_password [fritzbox password] + #%# family=auto contrib #%# capabilities=autoconf """ @@ -17,37 +23,41 @@ import os import sys -from fritzconnection import FritzConnection +from fritzconnection.lib.fritzstatus import FritzStatus + +server = os.environ["fritzbox_ip"] +username = os.environ["fritzbox_username"] +password = os.environ["fritzbox_password"] def print_values(): try: - conn = FritzConnection(address=os.environ['fritzbox_ip']) + fs = FritzStatus(address=server, user=username, password=password) except Exception as e: sys.exit("Couldn't get connection uptime") - uptime = conn.call_action('WANIPConnection', 'GetStatusInfo')['NewUptime'] - print('uptime.value %.2f' % (int(uptime) / 86400.0)) + uptime = fs.uptime + print("uptime.value %.2f" % (int(uptime) / 86400.0)) def print_config(): print("graph_title AVM Fritz!Box Connection Uptime") print("graph_args --base 1000 -l 0") - print('graph_vlabel uptime in days') + print("graph_vlabel uptime in days") print("graph_scale no'") print("graph_category network") print("uptime.label uptime") print("uptime.draw AREA") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) if __name__ == "__main__": - if len(sys.argv) == 2 and sys.argv[1] == 'config': + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": print("yes") # Some docs say it'll be called with fetch, some say no arg at all - elif len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] == 'fetch'): + elif len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] == "fetch"): try: print_values() except: diff --git a/fritzbox_cpu_temperature.py b/fritzbox_cpu_temperature.py index d38015a..fe8a9b7 100755 --- a/fritzbox_cpu_temperature.py +++ b/fritzbox_cpu_temperature.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_cpu_temperature - A munin plugin for Linux to monitor AVM Fritzbox Copyright (C) 2015 Christian Stade-Schuldt @@ -9,6 +9,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -20,19 +21,20 @@ import os import sys import fritzbox_helper as fh -PAGE = 'ecoStat' +PAGE = "ecoStat" def get_cpu_temperature(): """get the current cpu temperature""" - server = os.environ['fritzbox_ip'] - password = os.environ['fritzbox_password'] + server = os.environ["fritzbox_ip"] + username = os.environ["fritzbox_username"] + password = os.environ["fritzbox_password"] - session_id = fh.get_session_id(server, password) + session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) - print('temp.value %d' % (int(data['data']['cputemp']['series'][0][-1]))) + print("temp.value %d" % (int(data["data"]["cputemp"]["series"][0][-1]))) def print_config(): @@ -46,15 +48,15 @@ def print_config(): print("temp.graph LINE1") print("temp.min 0") print("temp.info Fritzbox CPU temperature") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) -if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'config': +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': - print('yes') - elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == 'fetch': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": + print("yes") + elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == "fetch": # Some docs say it'll be called with fetch, some say no arg at all get_cpu_temperature() diff --git a/fritzbox_cpu_usage.py b/fritzbox_cpu_usage.py index 4f56321..e108bf3 100755 --- a/fritzbox_cpu_usage.py +++ b/fritzbox_cpu_usage.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_cpu_usage - A munin plugin for Linux to monitor AVM Fritzbox Copyright (C) 2015 Christian Stade-Schuldt @@ -9,6 +9,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -20,19 +21,20 @@ import os import sys import fritzbox_helper as fh -PAGE = 'ecoStat' +PAGE = "ecoStat" def get_cpu_usage(): """get the current cpu usage""" - server = os.environ['fritzbox_ip'] - password = os.environ['fritzbox_password'] + server = os.environ["fritzbox_ip"] + username = os.environ["fritzbox_username"] + password = os.environ["fritzbox_password"] - session_id = fh.get_session_id(server, password) + session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) - print('cpu.value %d' % (int(data['data']['cpuutil']['series'][0][-1]))) + print("cpu.value %d" % (int(data["data"]["cpuutil"]["series"][0][-1]))) def print_config(): @@ -46,16 +48,16 @@ def print_config(): print("cpu.graph AREA") print("cpu.min 0") print("cpu.info Fritzbox CPU usage") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) -if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'config': +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': - print('yes') - elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == 'fetch': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": + print("yes") + elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == "fetch": # Some docs say it'll be called with fetch, some say no arg at all try: get_cpu_usage() diff --git a/fritzbox_helper.py b/fritzbox_helper.py index 7c9fcd3..a607541 100755 --- a/fritzbox_helper.py +++ b/fritzbox_helper.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_helper - A munin plugin for Linux to monitor AVM Fritzbox Copyright (C) 2015 Christian Stade-Schuldt @@ -9,6 +9,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -18,69 +19,102 @@ The initial script was inspired by https://www.linux-tips-and-tricks.de/en/programming/389-read-data-from-a-fritzbox-7390-with-python-and-bash framp at linux-tips-and-tricks dot de + + New authentication supporting username and password, as well as PBKDF2 support, has been inspired by + https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AVM%20Technical%20Note%20-%20Session%20ID_englisch.pdf """ import hashlib import sys +import time import requests from lxml import etree USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" +LOGIN_SID_ROUTE = "/login_sid.lua?version=2" -def get_session_id(server, password, port=80): - """Obtains the session id after login into the Fritzbox. - See https://avm.de/fileadmin/user_upload/Global/Service/Schnittstellen/AVM_Technical_Note_-_Session_ID.pdf - for deteils (in German). - :param server: the ip address of the Fritzbox - :param password: the password to log into the Fritzbox webinterface - :param port: the port the Fritzbox webserver runs on - :return: the session id - """ +class LoginState: + def __init__(self, challenge, blocktime): + self.challenge = challenge + self.blocktime = blocktime + self.is_pbkdf2 = challenge.startswith("2$") - headers = {"Accept": "application/xml", - "Content-Type": "text/plain", - "User-Agent": USER_AGENT} - url = 'http://{}:{}/login_sid.lua'.format(server, port) +def get_session_id(server, username, password, port=80): + """ Get a sid by solving the PBKDF2 (or MD5) challenge-response process. """ + box_url = "http://{}:{}".format(server, port) try: - r = requests.get(url, headers=headers) - r.raise_for_status() - except requests.exceptions.HTTPError as err: - print(err) - sys.exit(1) - - root = etree.fromstring(r.content) - session_id = root.xpath('//SessionInfo/SID/text()')[0] - if session_id == "0000000000000000": - challenge = root.xpath('//SessionInfo/Challenge/text()')[0] - challenge_bf = ('{}-{}'.format(challenge, password)).encode('utf-16le') - m = hashlib.md5() - m.update(challenge_bf) - response_bf = '{}-{}'.format(challenge, m.hexdigest().lower()) + state = get_login_state(box_url) + except Exception as ex: + raise Exception("failed to get challenge") + if state.is_pbkdf2: + # print("PBKDF2 supported") + challenge_response = calculate_pbkdf2_response(state.challenge, password) else: - return session_id - - headers = {"Accept": "text/html,application/xhtml+xml,application/xml", - "Content-Type": "application/x-www-form-urlencoded", - "User-Agent": USER_AGENT} - - url = 'http://{}:{}/login_sid.lua?&response={}'.format(server, port, response_bf) + # print("Falling back to MD5") + challenge_response = calculate_md5_response(state.challenge, password) + if state.blocktime > 0: + # print(f"Waiting for {state.blocktime} seconds...") + time.sleep(state.blocktime) try: - r = requests.get(url, headers=headers) - r.raise_for_status() - except requests.exceptions.HTTPError as err: - print(err) - sys.exit(1) + sid = send_response(box_url, username, challenge_response) + except Exception as ex: + raise Exception("failed to login") from ex + if sid == "0000000000000000": + raise Exception("wrong username or password") + return sid - root = etree.fromstring(r.content) - session_id = root.xpath('//SessionInfo/SID/text()')[0] - if session_id == "0000000000000000": - print("ERROR - No SID received because of invalid password") - sys.exit(0) - return session_id + +def get_login_state(box_url): + """ Get login state from FRITZ!Box using login_sid.lua?version=2 """ + url = box_url + LOGIN_SID_ROUTE + r = requests.get(url) + xml = etree.fromstring(r.content) + challenge = xml.find("Challenge").text + blocktime = int(xml.find("BlockTime").text) + return LoginState(challenge, blocktime) + + +def calculate_pbkdf2_response(challenge, password): + """ Calculate the response for a given challenge via PBKDF2 """ + challenge_parts = challenge.split("$") + # Extract all necessary values encoded into the challenge + iter1 = int(challenge_parts[1]) + salt1 = bytes.fromhex(challenge_parts[2]) + iter2 = int(challenge_parts[3]) + salt2 = bytes.fromhex(challenge_parts[4]) + # Hash twice, once with static salt... + # Once with dynamic salt. + hash1 = hashlib.pbkdf2_hmac("sha256", password.encode(), salt1, iter1) + hash2 = hashlib.pbkdf2_hmac("sha256", hash1, salt2, iter2) + return f"{challenge_parts[4]}${hash2.hex()}" + + +def calculate_md5_response(challenge, password): + """ Calculate the response for a challenge using legacy MD5 """ + response = challenge + "-" + password + # the legacy response needs utf_16_le encoding + response = response.encode("utf_16_le") + md5_sum = hashlib.md5() + md5_sum.update(response) + response = challenge + "-" + md5_sum.hexdigest() + return response + + +def send_response(box_url, username, challenge_response): + """ Send the response and return the parsed sid. raises an Exception on error """ + # Build response params + post_data = {"username": username, "response": challenge_response} + # post_data = urllib.parse.urlencode(post_data_dict).encode() + headers = {"Content-Type": "application/x-www-form-urlencoded"} + url = box_url + LOGIN_SID_ROUTE + r = requests.post(url, headers=headers, data=post_data) + # Parse SID from resulting XML. + xml = etree.fromstring(r.content) + return xml.find("SID").text def get_page_content(server, session_id, page, port=80): @@ -93,11 +127,9 @@ def get_page_content(server, session_id, page, port=80): :return: the content of the page """ - headers = {"Accept": "application/xml", - "Content-Type": "text/plain", - "User-Agent": USER_AGENT} + headers = {"Accept": "application/xml", "Content-Type": "text/plain", "User-Agent": USER_AGENT} - url = 'http://{}:{}/{}?sid={}'.format(server, port, page, session_id) + url = "http://{}:{}/{}?sid={}".format(server, port, page, session_id) try: r = requests.get(url, headers=headers) r.raise_for_status() @@ -117,18 +149,14 @@ def get_xhr_content(server, session_id, page, port=80): :return: the content of the page """ - headers = {"Accept": "application/xml", - "Content-Type": "application/x-www-form-urlencoded", - "User-Agent": USER_AGENT} + headers = { + "Accept": "application/xml", + "Content-Type": "application/x-www-form-urlencoded", + "User-Agent": USER_AGENT, + } - url = 'http://{}:{}/data.lua'.format(server, port) - data = {"xhr": 1, - "sid": session_id, - "lang": "en", - "page": page, - "xhrId": "all", - "no_sidrenew": "" - } + url = "http://{}:{}/data.lua".format(server, port) + data = {"xhr": 1, "sid": session_id, "lang": "en", "page": page, "xhrId": "all", "no_sidrenew": ""} try: r = requests.post(url, data=data, headers=headers) except requests.exceptions.HTTPError as err: diff --git a/fritzbox_memory_usage.py b/fritzbox_memory_usage.py index a73d13b..047131d 100755 --- a/fritzbox_memory_usage.py +++ b/fritzbox_memory_usage.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_memory_usage - A munin plugin for Linux to monitor AVM Fritzbox Copyright (C) 2015 Christian Stade-Schuldt @@ -9,6 +9,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -20,21 +21,22 @@ import os import sys import fritzbox_helper as fh -PAGE = 'ecoStat' -USAGE = ['strict', 'cache', 'free'] +PAGE = "ecoStat" +USAGE = ["strict", "cache", "free"] def get_memory_usage(): """get the current memory usage""" - server = os.environ['fritzbox_ip'] - password = os.environ['fritzbox_password'] + server = os.environ["fritzbox_ip"] + username = os.environ["fritzbox_username"] + password = os.environ["fritzbox_password"] - session_id = fh.get_session_id(server, password) + session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) for i, usage in enumerate(USAGE): - print('%s.value %s' % (usage, data['data']['ramusage']['series'][i][-1])) + print("%s.value %s" % (usage, data["data"]["ramusage"]["series"][i][-1])) def print_config(): @@ -54,16 +56,16 @@ def print_config(): print("free.label free") print("free.type GAUGE") print("free.draw STACK") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) -if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'config': +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': - print('yes') - elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == 'fetch': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": + print("yes") + elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == "fetch": # Some docs say it'll be called with fetch, some say no arg at all try: get_memory_usage() diff --git a/fritzbox_power_consumption.py b/fritzbox_power_consumption.py index 9d71a76..fd11f68 100755 --- a/fritzbox_power_consumption.py +++ b/fritzbox_power_consumption.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # coding=utf-8 """ fritzbox_power_consumption - A munin plugin for Linux to monitor AVM Fritzbox @@ -10,6 +10,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -22,22 +23,23 @@ import sys import fritzbox_helper as fh -PAGE = 'energy' -DEVICES = ['system', 'cpu', 'wifi', 'dsl', 'ab', 'usb'] +PAGE = "energy" +DEVICES = ["system", "cpu", "wifi", "dsl", "ab", "usb"] def get_power_consumption(): """get the current power consumption usage""" - server = os.environ['fritzbox_ip'] - password = os.environ['fritzbox_password'] + server = os.environ["fritzbox_ip"] + username = os.environ["fritzbox_username"] + password = os.environ["fritzbox_password"] - session_id = fh.get_session_id(server, password) + session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) - devices = data['data']['drain'] + devices = data["data"]["drain"] for i, device in enumerate(DEVICES): - print('%s.value %s' % (device, devices[i]['actPerc'])) + print("%s.value %s" % (device, devices[i]["actPerc"])) def print_config(): @@ -81,16 +83,16 @@ def print_config(): print("usb.min 0") print("usb.max 100") print("usb.info Fritzbox usb devices power consumption") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) -if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'config': +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': - print('yes') - elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == 'fetch': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": + print("yes") + elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == "fetch": # Some docs say it'll be called with fetch, some say no arg at all try: get_power_consumption() diff --git a/fritzbox_traffic.py b/fritzbox_traffic.py index 25ccb24..bb81184 100755 --- a/fritzbox_traffic.py +++ b/fritzbox_traffic.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_traffic - A munin plugin for Linux to monitor AVM Fritzbox WAN traffic Copyright (C) 2015 Christian Stade-Schuldt @@ -10,6 +10,12 @@ This plugin requires the fritzconnection plugin. To install it using pip: pip install fritzconnection This plugin supports the following munin configuration parameters: + + [fritzbox_*] + env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] + env.fritzbox_password [fritzbox password] + #%# family=auto contrib #%# capabilities=autoconf """ @@ -17,29 +23,33 @@ import os import sys -from fritzconnection import FritzConnection +from fritzconnection.lib.fritzstatus import FritzStatus + +server = os.environ["fritzbox_ip"] +username = os.environ["fritzbox_username"] +password = os.environ["fritzbox_password"] def print_values(): try: - conn = FritzConnection(address=os.environ['fritzbox_ip']) + fs = FritzStatus(address=server, user=username, password=password) except Exception as e: sys.exit("Couldn't get WAN traffic") - down_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetTotalBytesReceived')['NewTotalBytesReceived'] - print('down.value %d' % down_traffic) + traffic = fs.transmission_rate + down_traffic = traffic[1] + print("down.value %d" % down_traffic) - up_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetTotalBytesSent')['NewTotalBytesSent'] - print('up.value %d' % up_traffic) + up_traffic = traffic[0] + print("up.value %d" % up_traffic) - if not os.environ.get('traffic_remove_max'): - max_down_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetCommonLinkProperties')[ - 'NewLayer1DownstreamMaxBitRate'] - print('maxdown.value %d' % max_down_traffic) + if not os.environ.get("traffic_remove_max"): + max_traffic = fs.max_bit_rate + max_down_traffic = max_traffic[1] + print("maxdown.value %d" % max_down_traffic) - max_up_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetCommonLinkProperties')[ - 'NewLayer1UpstreamMaxBitRate'] - print('maxup.value %d' % max_up_traffic) + max_up_traffic = max_traffic[0] + print("maxup.value %d" % max_up_traffic) def print_config(): @@ -62,7 +72,7 @@ def print_config(): print("up.max 1000000000") print("up.negative down") print("up.info Traffic of the WAN interface.") - if not os.environ.get('traffic_remove_max'): + if not os.environ.get("traffic_remove_max"): print("maxdown.label received") print("maxdown.type GAUGE") print("maxdown.graph no") @@ -71,16 +81,16 @@ def print_config(): print("maxup.negative maxdown") print("maxup.draw LINE1") print("maxup.info Maximum speed of the WAN interface.") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) if __name__ == "__main__": - if len(sys.argv) == 2 and sys.argv[1] == 'config': + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": print("yes") # Some docs say it'll be called with fetch, some say no arg at all - elif len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] == 'fetch'): + elif len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] == "fetch"): try: print_values() except: diff --git a/fritzbox_uptime.py b/fritzbox_uptime.py index 649c0d0..5a44af4 100755 --- a/fritzbox_uptime.py +++ b/fritzbox_uptime.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_uptime - A munin plugin for Linux to monitor AVM Fritzbox Copyright (C) 2015 Christian Stade-Schuldt @@ -9,6 +9,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -22,29 +23,29 @@ import sys import fritzbox_helper as fh -locale = os.environ.get('locale', 'de') -patternLoc = {"de": r"(\d+)\s(Tag|Stunden|Minuten)", - "en": r"(\d+)\s(days|hours|minutes)"} +locale = os.environ.get("locale", "de") +patternLoc = {"de": r"(\d+)\s(Tag|Stunden|Minuten)", "en": r"(\d+)\s(days|hours|minutes)"} dayLoc = {"de": "Tag", "en": "days"} hourLoc = {"de": "Stunden", "en": "hours"} minutesLoc = {"de": "Minuten", "en": "minutes"} -PAGE = 'energy' +PAGE = "energy" pattern = re.compile(patternLoc[locale]) def get_uptime(): """get the current uptime""" - server = os.environ['fritzbox_ip'] - password = os.environ['fritzbox_password'] + server = os.environ["fritzbox_ip"] + username = os.environ["fritzbox_username"] + password = os.environ["fritzbox_password"] - session_id = fh.get_session_id(server, password) + session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) - for d in data['data']['drain']: - if 'aktiv' in d['statuses']: - matches = re.finditer(pattern, d['statuses']) + for d in data["data"]["drain"]: + if "aktiv" in d["statuses"]: + matches = re.finditer(pattern, d["statuses"]) if matches: hours = 0.0 for m in matches: @@ -61,21 +62,21 @@ def get_uptime(): def print_config(): print("graph_title AVM Fritz!Box Uptime") print("graph_args --base 1000 -l 0") - print('graph_vlabel uptime in days') + print("graph_vlabel uptime in days") print("graph_scale no'") print("graph_category system") print("uptime.label uptime") print("uptime.draw AREA") - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) -if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'config': +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': - print('yes') - elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == 'fetch': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": + print("yes") + elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == "fetch": # Some docs say it'll be called with fetch, some say no arg at all try: get_uptime() diff --git a/fritzbox_wifi_devices.py b/fritzbox_wifi_devices.py index bc8e24c..6c95a5b 100755 --- a/fritzbox_wifi_devices.py +++ b/fritzbox_wifi_devices.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ fritzbox_wifi_devices - A munin plugin for Linux to monitor AVM Fritzbox Copyright (C) 2015 Christian Stade-Schuldt @@ -9,6 +9,7 @@ [fritzbox_*] env.fritzbox_ip [ip address of the fritzbox] + env.fritzbox_username [fritzbox username] env.fritzbox_password [fritzbox password] This plugin supports the following munin configuration parameters: @@ -22,49 +23,49 @@ import sys import fritzbox_helper as fh -locale = os.environ.get('locale', 'de') -patternLoc = {"de": r"(\d+) WLAN", - "en": r"(\d+) wireless LAN"} +locale = os.environ.get("locale", "de") +patternLoc = {"de": r"(\d+) WLAN", "en": r"(\d+) wireless LAN"} -PAGE = 'energy' +PAGE = "energy" pattern = re.compile(patternLoc[locale]) def get_connected_wifi_devices(): """gets the numbrer of currently connected wifi devices""" - server = os.environ['fritzbox_ip'] - password = os.environ['fritzbox_password'] + server = os.environ["fritzbox_ip"] + username = os.environ["fritzbox_username"] + password = os.environ["fritzbox_password"] - session_id = fh.get_session_id(server, password) + session_id = fh.get_session_id(server, username, password) xhr_data = fh.get_xhr_content(server, session_id, PAGE) data = json.loads(xhr_data) - m = re.search(pattern, data['data']['drain'][2]['statuses'][-1]) + m = re.search(pattern, data["data"]["drain"][2]["statuses"][-1]) if m: connected_devices = int(m.group(1)) - print('wifi.value %d' % connected_devices) + print("wifi.value %d" % connected_devices) def print_config(): - print('graph_title AVM Fritz!Box Connected Wifi Devices') - print('graph_vlabel Number of devices') - print('graph_args --base 1000') - print('graph_category network') - print('graph_order wifi') - print('wifi.label Wifi Connections on 2.4 & 5 Ghz') - print('wifi.type GAUGE') - print('wifi.graph LINE1') - print('wifi.info Wifi Connections on 2.4 & 5 Ghz') - if os.environ.get('host_name'): - print("host_name " + os.environ['host_name']) + print("graph_title AVM Fritz!Box Connected Wifi Devices") + print("graph_vlabel Number of devices") + print("graph_args --base 1000") + print("graph_category network") + print("graph_order wifi") + print("wifi.label Wifi Connections on 2.4 & 5 Ghz") + print("wifi.type GAUGE") + print("wifi.graph LINE1") + print("wifi.info Wifi Connections on 2.4 & 5 Ghz") + if os.environ.get("host_name"): + print("host_name " + os.environ["host_name"]) -if __name__ == '__main__': - if len(sys.argv) == 2 and sys.argv[1] == 'config': +if __name__ == "__main__": + if len(sys.argv) == 2 and sys.argv[1] == "config": print_config() - elif len(sys.argv) == 2 and sys.argv[1] == 'autoconf': - print('yes') - elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == 'fetch': + elif len(sys.argv) == 2 and sys.argv[1] == "autoconf": + print("yes") + elif len(sys.argv) == 1 or len(sys.argv) == 2 and sys.argv[1] == "fetch": # Some docs say it'll be called with fetch, some say no arg at all try: get_connected_wifi_devices() diff --git a/requirements.txt b/requirements.txt index 0788e19..2eed26d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ fritzconnection lxml -requests \ No newline at end of file +requests