Skip to content

Commit

Permalink
extracted environment configuration into separate class in order to u…
Browse files Browse the repository at this point in the history
…se the tls flag everywhere consistently

Signed-off-by: Christoph Massmann <c.massmann@vianetz.com>
  • Loading branch information
ma4nn committed Nov 17, 2020
1 parent d57f071 commit 4b51389
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 36 deletions.
24 changes: 24 additions & 0 deletions FritzboxConfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import os

class FritzboxConfig:
"""the server address of the Fritzbox (ip or name)"""
server = "fritz.box"
"""the port the Fritzbox webserver runs on"""
port = 443
"""the user name to log into the Fritzbox webinterface"""
user = ""
"""the password to log into the Fritzbox webinterface"""
password = ""
useTls = True
certificateFile = os.getenv('MUNIN_CONFDIR') + '/box.cer'

# default constructor
def __init__(self):
if os.getenv('fritzbox_ip'):
self.server = os.getenv('fritzbox_ip')
self.user = os.getenv('fritzbox_user')
self.password = os.getenv('fritzbox_password')
if os.getenv('fritzbox_certificate'):
self.certificateFile = os.getenv('fritzbox_certificate')
if os.getenv('fritzbox_use_tls'):
self.useTls = os.getenv('fritzbox_use_tls') == 'true'
48 changes: 16 additions & 32 deletions FritzboxInterface.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,40 +30,24 @@

import requests
from lxml import etree
from FritzboxConfig import FritzboxConfig

class FritzboxInterface:
"""the server address of the Fritzbox (ip or name)"""
server = "fritz.box"
"""the port the Fritzbox webserver runs on"""
port = 443
"""the user name to log into the Fritzbox webinterface"""
user = ""
"""the password to log into the Fritzbox webinterface"""
password = ""
useTls = True
certificateFile = os.getenv('MUNIN_CONFDIR') + '/box.cer'

config = None
__baseUri = ""

# default constructor
def __init__(self):
if os.getenv('fritzbox_ip'):
self.server = os.getenv('fritzbox_ip')
self.user = os.getenv('fritzbox_user')
self.password = os.getenv('fritzbox_password')
if os.getenv('fritzbox_certificate'):
self.certificateFile = os.getenv('fritzbox_certificate')
self.__baseUri = self.__getBaseUri()
if os.getenv('fritzbox_use_tls'):
self.useTls = os.getenv('fritzbox_use_tls') == 'true'
self.config = FritzboxConfig()
self.__baseUri = self.__getBaseUri()

def __getBaseUri(self):
DEFAULT_PORTS = (80, 443)
SCHEMES = ('http', 'https')
if self.port and self.port != DEFAULT_PORTS[self.useTls]:
return '{}://{}:{}'.format(SCHEMES[self.useTls], self.server, self.port)
if self.config.port and self.config.port != DEFAULT_PORTS[self.config.useTls]:
return '{}://{}:{}'.format(SCHEMES[self.config.useTls], self.config.server, self.config.port)
else:
return '{}://{}'.format(SCHEMES[self.useTls], self.server)
return '{}://{}'.format(SCHEMES[self.config.useTls], self.config.server)

def getPageWithLogin(self, page, data={}):
return self.__callPageWithLogin(self.__get, page, data)
Expand All @@ -72,18 +56,18 @@ def postPageWithLogin(self, page, data={}):
return self.__callPageWithLogin(self.__post, page, data)

def __saveSessionId(self, session_id):
if '__' in self.server or '__' in self.user:
if '__' in self.config.server or '__' in self.config.user:
raise Exception("Reserved string \"__\" in server or user name")
statedir = os.getenv('MUNIN_PLUGSTATE') + '/fritzbox'
if not os.path.exists(statedir):
os.makedirs(statedir)
statefilename = statedir + '/' + self.server + '__' + str(self.port) + '__' + self.user + '.sid'
statefilename = statedir + '/' + self.config.server + '__' + str(self.config.port) + '__' + self.config.user + '.sid'
with open(statefilename, 'w') as statefile:
statefile.write(session_id)

def __loadSessionId(self):
statedir = os.getenv('MUNIN_PLUGSTATE') + '/fritzbox'
statefilename = statedir + '/' + self.server + '__' + str(self.port) + '__' + self.user + '.sid'
statefilename = statedir + '/' + self.config.server + '__' + str(self.config.port) + '__' + self.config.user + '.sid'
if not os.path.exists(statefilename):
return None
with open(statefilename, 'r') as statefile:
Expand All @@ -102,7 +86,7 @@ def __getSessionId(self):

url = '{}/login_sid.lua'.format(self.__baseUri)
try:
r = requests.get(url, headers=headers, verify=self.certificateFile)
r = requests.get(url, headers=headers, verify=self.config.certificateFile)
r.raise_for_status()
except (requests.exceptions.HTTPError, requests.exceptions.SSLError) as err:
print(err)
Expand All @@ -113,21 +97,21 @@ def __getSessionId(self):
session_id = root.xpath('//SessionInfo/SID/text()')[0]
if session_id == "0000000000000000":
challenge = root.xpath('//SessionInfo/Challenge/text()')[0]
challenge_bf = ('{}-{}'.format(challenge, self.password)).encode('utf-16le')
challenge_bf = ('{}-{}'.format(challenge, self.config.password)).encode('utf-16le')
m = hashlib.md5()
m.update(challenge_bf)
response_bf = '{}-{}'.format(challenge, m.hexdigest().lower())
params['response'] = response_bf
else:
return session_id

params['username'] = self.user
params['username'] = self.config.user

headers = {"Accept": "text/html,application/xhtml+xml,application/xml", "Content-Type": "application/x-www-form-urlencoded"}

url = '{}/login_sid.lua'.format(self.__baseUri)
try:
r = requests.get(url, headers=headers, params=params, verify=self.certificateFile)
r = requests.get(url, headers=headers, params=params, verify=self.config.certificateFile)
r.raise_for_status()
except (requests.exceptions.HTTPError, requests.exceptions.SSLError) as err:
print(err)
Expand Down Expand Up @@ -174,7 +158,7 @@ def __post(self, session_id, page, data={}):

url = '{}/{}'.format(self.__baseUri, page)

r = requests.post(url, headers=headers, data=data, verify=self.certificateFile)
r = requests.post(url, headers=headers, data=data, verify=self.config.certificateFile)
r.raise_for_status()

return r.content
Expand All @@ -194,7 +178,7 @@ def __get(self, session_id, page, data={}):
params["sid"] = session_id
url = '{}/{}'.format(self.__baseUri, page)

r = requests.get(url, headers=headers, params=params, verify=self.certificateFile)
r = requests.get(url, headers=headers, params=params, verify=self.config.certificateFile)
r.raise_for_status()

return r.content
4 changes: 3 additions & 1 deletion fritzbox_connection_uptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@
import os
import sys
from fritzconnection.lib.fritzstatus import FritzStatus
from FritzboxConfig import FritzboxConfig

class FritzboxConnectionUptime:
__connection = None

def __init__(self):
config = FritzboxConfig()
try:
self.__connection = FritzStatus(address=os.getenv('fritzbox_ip'), password=os.getenv('fritzbox_password'), use_tls=True)
self.__connection = FritzStatus(address=config.server, password=config.password, use_tls=config.useTls)
except Exception as e:
sys.exit("Couldn't get connection uptime: " + str(e))

Expand Down
4 changes: 3 additions & 1 deletion fritzbox_smart_home_temperature.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import re
import sys
from fritzconnection import FritzConnection
from FritzboxConfig import FritzboxConfig

def printSmartHomeTemperature():
"""get the current cpu temperature"""
Expand All @@ -30,9 +31,10 @@ def printConfig():

def retrieveSmartHomeTemps():
smartHomeData = []
config = FritzboxConfig()

try:
connection = FritzConnection(address=os.getenv('fritzbox_ip'), password=os.getenv('fritzbox_password'), use_tls=True)
connection = FritzConnection(address=config.server, password=config.password, use_tls=config.useTls)
except Exception as e:
sys.exit("Couldn't get temperature: " + str(e))

Expand Down
8 changes: 6 additions & 2 deletions fritzbox_traffic.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,13 @@
import os
import sys
from fritzconnection.lib.fritzstatus import FritzStatus
from FritzboxConfig import FritzboxConfig

def print_traffic():
config = FritzboxConfig()

try:
conn = FritzStatus(address=os.getenv('fritzbox_ip'), password=os.getenv('fritzbox_password'), use_tls=True)
conn = FritzStatus(address=config.server, password=config.password, use_tls=config.useTls)
except Exception as e:
sys.exit("Couldn't get WAN traffic: " + str(e))

Expand All @@ -39,8 +42,9 @@ def print_traffic():
print('maxup.value %d' % max_traffic[0])

def print_config():
config = FritzboxConfig()
try:
conn = FritzStatus(address=os.getenv('fritzbox_ip'), password=os.getenv('fritzbox_password'), use_tls=True)
conn = FritzStatus(address=config.server, password=config.password, use_tls=config.useTls)
except Exception as e:
print(e)
sys.exit("Couldn't get WAN traffic: " + str(e))
Expand Down

0 comments on commit 4b51389

Please sign in to comment.