Python 3 and FritzBox 7.x adaptions

This commit is contained in:
Bernd Oerding 2020-11-08 14:31:36 +01:00
parent a12ac558c1
commit 9030a0bf45
10 changed files with 139 additions and 78 deletions

View File

@ -21,12 +21,26 @@ from fritzconnection import FritzConnection
def print_values():
try:
conn = FritzConnection(address=os.environ['fritzbox_ip'])
except Exception as e:
sys.exit("Couldn't get connection uptime")
server = os.environ['fritzbox_ip']
if 'fritzbox_port' in os.environ :
port = os.environ['fritzbox_port']
else :
port = None
if 'fritzbox_user' in os.environ :
user = os.environ['fritzbox_user']
else :
user = None
if 'fritzbox_password' in os.environ :
password = os.environ['fritzbox_password']
else:
password = None
uptime = conn.call_action('WANIPConnection', 'GetStatusInfo')['NewUptime']
try:
conn = FritzConnection(address=server, port=port, user=user, password=password)
except Exception as e:
sys.exit("Couldn't get connection uptime", e)
uptime = conn.call_action('WANIPConn', 'GetStatusInfo')['NewUptime']
print('uptime.value %.2f' % (int(uptime) / 86400.0))
@ -48,7 +62,7 @@ if __name__ == "__main__":
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'):
try:
try:
print_values()
except:
sys.exit("Couldn't retrieve fritzbox connection uptime")

View File

@ -19,24 +19,21 @@
"""
import os
import re
import sys
import fritzbox_helper as fh
import json
PAGE = '/system/ecostat.lua'
pattern = re.compile('Query\s=\s"(\d{1,3})')
PAGE = 'ecoStat'
def get_cpu_temperature():
"""get the current cpu temperature"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
m = re.search(pattern, data)
if m:
print('temp.value %d' % (int(m.group(1))))
xhr_data = fh.get_xhr_content(session_id, PAGE)
data = json.loads(xhr_data)
print('temp.value %d' % (int(data['data']['cputemp']['series'][0][-1])))
def print_config():
print("graph_title AVM Fritz!Box CPU temperature")

View File

@ -19,24 +19,20 @@
"""
import os
import re
import sys
import fritzbox_helper as fh
import json
PAGE = '/system/ecostat.lua'
pattern = re.compile('Query1\s=\s"(\d{1,3})')
PAGE = 'ecoStat'
def get_cpu_usage():
"""get the current cpu usage"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
m = re.search(pattern, data)
if m:
print('cpu.value %d' % (int(m.group(1))))
xhr_data = fh.get_xhr_content(session_id, PAGE)
data = json.loads(xhr_data)
print('cpu.value %d' % (int(data['data']['cpuutil']['series'][0][-1])))
def print_config():
print("graph_title AVM Fritz!Box CPU usage")
@ -50,7 +46,7 @@ def print_config():
print("cpu.min 0")
print("cpu.info Fritzbox CPU usage")
if os.environ.get('host_name'):
print "host_name " + os.environ['host_name']
print ("host_name " + os.environ['host_name'])
if __name__ == '__main__':

View File

@ -67,7 +67,8 @@ def get_session_id():
session_id = root.xpath('//SessionInfo/SID/text()')[0]
if session_id == "0000000000000000":
challenge = root.xpath('//SessionInfo/Challenge/text()')[0]
challenge_bf = ('{}-{}'.format(challenge, password)).decode('iso-8859-1').encode('utf-16le')
# challenge_bf = ('{}-{}'.format(challenge, password)).decode('iso-8859-1').encode('utf-16le')
challenge_bf = ('{}-{}'.format(challenge, password)).encode('utf-16le')
m = hashlib.md5()
m.update(challenge_bf)
response_bf = '{}-{}'.format(challenge, m.hexdigest().lower())
@ -126,3 +127,36 @@ def get_page_content(session_id, page):
sys.exit(1)
return r.content
def get_xhr_content(session_id, page):
"""Fetches the xhr content from the Fritzbox and returns its content
:param server: the ip address of the Fritzbox
:param session_id: a valid session id
:param page: the page you are requesting
:param port: the port the Fritzbox webserver runs on
:return: the content of the page
"""
server = os.environ['fritzbox_ip']
if 'fritzbox_port' in os.environ :
port = os.environ['fritzbox_port']
else :
port = 80
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": ""
}
try:
r = requests.post(url, data=data, headers=headers)
except requests.exceptions.HTTPError as err:
print(err)
sys.exit(1)
return r.content

View File

@ -19,12 +19,11 @@
"""
import os
import re
import sys
import fritzbox_helper as fh
import json
PAGE = '/system/ecostat.lua'
pattern = re.compile('Query[1-3]\s="(\d{1,3})')
PAGE = 'ecoStat'
USAGE = ['free', 'cache', 'strict']
@ -32,12 +31,10 @@ def get_memory_usage():
"""get the current memory usage"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
matches = re.finditer(pattern, data)
if matches:
data = zip(USAGE, [m.group(1) for m in matches])
for d in data:
print('%s.value %s' % (d[0], d[1]))
xhr_data = fh.get_xhr_content(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]))
def print_config():

View File

@ -19,12 +19,11 @@
"""
import os
import re
import sys
import fritzbox_helper as fh
import json
PAGE = '/system/energy.lua'
pattern = re.compile('<td>(.+?)"bar\s(act|fillonly)"(.+?)\s(\d{1,3})\s%')
PAGE = 'energy'
DEVICES = ['system', 'cpu', 'wifi', 'dsl', 'ab', 'usb']
@ -32,12 +31,11 @@ def get_power_consumption():
"""get the current power consumption usage"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
matches = re.finditer(pattern, data)
if matches:
data = zip(DEVICES, [m.group(4) for m in matches])
for d in data:
print('%s.value %s' % (d[0], d[1]))
xhr_data = fh.get_xhr_content(session_id, PAGE)
data = json.loads(xhr_data)
devices = data['data']['drain']
for i, device in enumerate(DEVICES):
print('%s.value %s' % (device, devices[i]['actPerc']))
def print_config():

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
"""
fritzbox_smart_home_temperature - A munin plugin for Linux to monitor AVM Fritzbox SmartHome temperatures
Copyright (C) 2018 Bernd Oerding
Copyright (C) 2018-2020 Bernd Oerding
Author: Bernd Oerding
Like Munin, this plugin is licensed under the GNU GPL v2 license
http://www.opensource.org/licenses/GPL-2.0
@ -29,7 +29,7 @@ PAGE = 'webservices/homeautoswitch.lua?switchcmd=getdevicelistinfos'
def get_smart_home_temperature(debug=False):
"""get the current cpu temperature"""
"""get the current temperature"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
@ -40,8 +40,10 @@ def get_smart_home_temperature(debug=False):
id = d.xpath("@id")[0]
present = int(d.xpath("present/text()")[0])
if present :
temp= float(d.xpath("temperature/celsius/text()")[0])/10
print ("t{}.value {}".format(id,temp))
temp =d.xpath("temperature/celsius/text()")
if len(temp) > 0 :
temp= float(d.xpath("temperature/celsius/text()")[0])/10
print ("t{}.value {}".format(id,temp))
def print_config():
@ -60,13 +62,15 @@ def print_config():
id = d.xpath("@id")[0]
identifier = d.xpath("@identifier")[0]
name = d.xpath("name/text()")[0]
name = unidecode(unicode(name))
# name = unidecode(unicode(name))
name = unidecode(name)
pname = d.xpath("@productname")[0]
print ("t{}.label {}".format(id,name))
print ("t{}.type GAUGE".format(id))
print ("t{}.graph LINE".format(id))
print ("t{}.info Temperature [{} - {}]".format(id,pname,identifier))
temp =d.xpath("temperature/celsius/text()")
if len(temp) > 0 :
print ("t{}.label {}".format(id,name))
print ("t{}.type GAUGE".format(id))
print ("t{}.graph LINE".format(id))
print ("t{}.info Temperature [{} - {}]".format(id,pname,identifier))
if os.environ.get('host_name'):
print("host_name " + os.environ['host_name'])

View File

@ -21,23 +21,37 @@ from fritzconnection import FritzConnection
def print_values():
server = os.environ['fritzbox_ip']
if 'fritzbox_port' in os.environ :
port = os.environ['fritzbox_port']
else :
port = None
if 'fritzbox_user' in os.environ :
user = os.environ['fritzbox_user']
else :
user = None
if 'fritzbox_password' in os.environ :
password = os.environ['fritzbox_password']
else:
password = None
try:
conn = FritzConnection(address=os.environ['fritzbox_ip'])
conn = FritzConnection(address=os.environ['fritzbox_ip'], port=port, user=user, password=password)
except Exception as e:
sys.exit("Couldn't get WAN traffic")
down_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetTotalBytesReceived')['NewTotalBytesReceived']
down_traffic = conn.call_action('WANCommonIFC', 'GetTotalBytesReceived')['NewTotalBytesReceived']
print('down.value %d' % down_traffic)
up_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetTotalBytesSent')['NewTotalBytesSent']
up_traffic = conn.call_action('WANCommonIFC', 'GetTotalBytesSent')['NewTotalBytesSent']
print('up.value %d' % up_traffic)
if not os.environ.get('traffic_remove_max'):
max_down_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetCommonLinkProperties')[
max_down_traffic = conn.call_action('WANCommonIFC', 'GetCommonLinkProperties')[
'NewLayer1DownstreamMaxBitRate']
print('maxdown.value %d' % max_down_traffic)
max_up_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetCommonLinkProperties')[
max_up_traffic = conn.call_action('WANCommonIFC', 'GetCommonLinkProperties')[
'NewLayer1UpstreamMaxBitRate']
print('maxup.value %d' % max_up_traffic)

View File

@ -23,6 +23,7 @@ import re
import sys
import fritzbox_helper as fh
import json
locale = os.environ.get('locale', 'de')
patternLoc = {"de": "(\d+)\s(Tag|Stunden|Minuten)",
@ -31,7 +32,7 @@ dayLoc = {"de": "Tag", "en": "days"}
hourLoc = {"de": "Stunden", "en": "hours"}
minutesLoc = {"de": "Minuten", "en": "minutes"}
PAGE = '/system/energy.lua'
PAGE = 'energy'
pattern = re.compile(patternLoc[locale])
@ -39,20 +40,23 @@ def get_uptime():
"""get the current uptime"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
matches = re.finditer(pattern, data)
if matches:
hours = 0.0
for m in matches:
if m.group(2) == dayLoc[locale]:
hours += 24 * int(m.group(1))
if m.group(2) == hourLoc[locale]:
hours += int(m.group(1))
if m.group(2) == minutesLoc[locale]:
hours += int(m.group(1)) / 60.0
uptime = hours / 24
print "uptime.value %.2f" % uptime
xhr_data = fh.get_xhr_content(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'])
if matches:
hours = 0.0
for m in matches:
if m.group(2) == dayLoc[locale]:
hours += 24 * int(m.group(1))
if m.group(2) == hourLoc[locale]:
hours += int(m.group(1))
if m.group(2) == minutesLoc[locale]:
hours += int(m.group(1)) / 60.0
uptime = hours / 24
print("uptime.value %.2f" % uptime)
def print_config():
print("graph_title AVM Fritz!Box Uptime")

View File

@ -24,10 +24,12 @@ import sys
import fritzbox_helper as fh
import json
locale = os.environ.get('locale', 'de')
patternLoc = {"de": "(\d+) WLAN", "en": "(\d+) wireless LAN"}
PAGE = '/system/energy.lua'
PAGE = 'energy'
pattern = re.compile(patternLoc[locale])
@ -35,12 +37,13 @@ def get_connected_wifi_devices():
"""gets the numbrer of currently connected wifi devices"""
session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE)
m = re.search(pattern, data)
xhr_data = fh.get_xhr_content(session_id, PAGE)
data = json.loads(xhr_data)
m = re.search(pattern, data['data']['drain'][2]['statuses'][-1])
if m:
connected_devices = int(m.group(1))
print('wifi.value %d' % connected_devices)
def print_config():
print('graph_title AVM Fritz!Box Connected Wifi Devices')