1
0
mirror of https://github.com/Tafkas/fritzbox-munin.git synced 2023-10-10 11:36:55 +00:00

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(): def print_values():
try: server = os.environ['fritzbox_ip']
conn = FritzConnection(address=os.environ['fritzbox_ip']) if 'fritzbox_port' in os.environ :
except Exception as e: port = os.environ['fritzbox_port']
sys.exit("Couldn't get connection uptime") 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)) print('uptime.value %.2f' % (int(uptime) / 86400.0))

View File

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

View File

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

View File

@ -67,7 +67,8 @@ def get_session_id():
session_id = root.xpath('//SessionInfo/SID/text()')[0] session_id = root.xpath('//SessionInfo/SID/text()')[0]
if session_id == "0000000000000000": if session_id == "0000000000000000":
challenge = root.xpath('//SessionInfo/Challenge/text()')[0] 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 = hashlib.md5()
m.update(challenge_bf) m.update(challenge_bf)
response_bf = '{}-{}'.format(challenge, m.hexdigest().lower()) response_bf = '{}-{}'.format(challenge, m.hexdigest().lower())
@ -126,3 +127,36 @@ def get_page_content(session_id, page):
sys.exit(1) sys.exit(1)
return r.content 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 os
import re
import sys import sys
import fritzbox_helper as fh import fritzbox_helper as fh
import json
PAGE = '/system/ecostat.lua' PAGE = 'ecoStat'
pattern = re.compile('Query[1-3]\s="(\d{1,3})')
USAGE = ['free', 'cache', 'strict'] USAGE = ['free', 'cache', 'strict']
@ -32,12 +31,10 @@ def get_memory_usage():
"""get the current memory usage""" """get the current memory usage"""
session_id = fh.get_session_id() session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE) xhr_data = fh.get_xhr_content(session_id, PAGE)
matches = re.finditer(pattern, data) data = json.loads(xhr_data)
if matches: for i, usage in enumerate(USAGE):
data = zip(USAGE, [m.group(1) for m in matches]) print('%s.value %s' % (usage, data['data']['ramusage']['series'][i][-1]))
for d in data:
print('%s.value %s' % (d[0], d[1]))
def print_config(): def print_config():

View File

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

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
""" """
fritzbox_smart_home_temperature - A munin plugin for Linux to monitor AVM Fritzbox SmartHome temperatures 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 Author: Bernd Oerding
Like Munin, this plugin is licensed under the GNU GPL v2 license Like Munin, this plugin is licensed under the GNU GPL v2 license
http://www.opensource.org/licenses/GPL-2.0 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): def get_smart_home_temperature(debug=False):
"""get the current cpu temperature""" """get the current temperature"""
session_id = fh.get_session_id() session_id = fh.get_session_id()
data = fh.get_page_content(session_id, PAGE) data = fh.get_page_content(session_id, PAGE)
@ -40,6 +40,8 @@ def get_smart_home_temperature(debug=False):
id = d.xpath("@id")[0] id = d.xpath("@id")[0]
present = int(d.xpath("present/text()")[0]) present = int(d.xpath("present/text()")[0])
if present : if present :
temp =d.xpath("temperature/celsius/text()")
if len(temp) > 0 :
temp= float(d.xpath("temperature/celsius/text()")[0])/10 temp= float(d.xpath("temperature/celsius/text()")[0])/10
print ("t{}.value {}".format(id,temp)) print ("t{}.value {}".format(id,temp))
@ -60,9 +62,11 @@ def print_config():
id = d.xpath("@id")[0] id = d.xpath("@id")[0]
identifier = d.xpath("@identifier")[0] identifier = d.xpath("@identifier")[0]
name = d.xpath("name/text()")[0] name = d.xpath("name/text()")[0]
name = unidecode(unicode(name)) # name = unidecode(unicode(name))
name = unidecode(name)
pname = d.xpath("@productname")[0] pname = d.xpath("@productname")[0]
temp =d.xpath("temperature/celsius/text()")
if len(temp) > 0 :
print ("t{}.label {}".format(id,name)) print ("t{}.label {}".format(id,name))
print ("t{}.type GAUGE".format(id)) print ("t{}.type GAUGE".format(id))
print ("t{}.graph LINE".format(id)) print ("t{}.graph LINE".format(id))

View File

@ -21,23 +21,37 @@ from fritzconnection import FritzConnection
def print_values(): 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: 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: except Exception as e:
sys.exit("Couldn't get WAN traffic") 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) 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) print('up.value %d' % up_traffic)
if not os.environ.get('traffic_remove_max'): 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'] 'NewLayer1DownstreamMaxBitRate']
print('maxdown.value %d' % max_down_traffic) print('maxdown.value %d' % max_down_traffic)
max_up_traffic = conn.call_action('WANCommonInterfaceConfig', 'GetCommonLinkProperties')[ max_up_traffic = conn.call_action('WANCommonIFC', 'GetCommonLinkProperties')[
'NewLayer1UpstreamMaxBitRate'] 'NewLayer1UpstreamMaxBitRate']
print('maxup.value %d' % max_up_traffic) print('maxup.value %d' % max_up_traffic)

View File

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

View File

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