Skip to content

Commit

Permalink
Use https connections
Browse files Browse the repository at this point in the history
  • Loading branch information
Andre0512 committed Feb 1, 2023
1 parent 094df01 commit 95c7ac3
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 19 deletions.
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@

setup(
name="speedport-api",
version="0.4.3",
version="0.4.4",
author="Andre Basche",
description="Control Telekom Speedport routers with Python",
long_description=long_description,
long_description_content_type='text/markdown',
url="https://github.com/Andre0512/speedport-api",
license="MIT",
platforms="any",
py_modules=["jeelink-python"],
package_dir={"": "src"},
packages=["speedport"],
include_package_data=True,
Expand Down
2 changes: 1 addition & 1 deletion src/speedport/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .speedport import Speedport
from .speedport import Speedport
8 changes: 7 additions & 1 deletion src/speedport/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
import sys
import time
from getpass import getpass
from pathlib import Path

if __name__ == "__main__":
sys.path.insert(0, str(Path(__file__).parent.parent))

from speedport import Speedport

Expand Down Expand Up @@ -42,6 +46,7 @@ def get_arguments():
"""Get parsed arguments."""
parser = argparse.ArgumentParser(description="Speedport: Command Line Utility")
parser.add_argument("-H", "--host", help="ip address or hostname of Speedport webinterface", default="speedport.ip")
parser.add_argument("-s", "--https", help="use https connection", action="store_true")
parser.add_argument("-p", "--password", help="password of Speedport webinterface")
parser.add_argument("-d", "--debug", help="enable debug logging", action="store_true")
parser.add_argument("-q", "--quiet", help="output only errors", action="store_true")
Expand All @@ -65,12 +70,13 @@ def get_arguments():
async def main():
args = get_arguments()
set_logger(args)
speedport = Speedport(args["host"])
speedport = Speedport(args["host"], args.get("https"))
if not args.get("devices"):
if not (password := args["password"]):
password = getpass("Password of Speedports webinterface: ")
if not await speedport.login(password=password):
print("Can't login! Wrong password?")
return
if args.get("wifi") and args["wifi"] == "on":
await speedport.wifi_on()
elif args.get("wifi") and args["wifi"] == "off":
Expand Down
29 changes: 14 additions & 15 deletions src/speedport/speedport.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@


class Speedport:
def __init__(self, host="speedport.ip"):
def __init__(self, host="speedport.ip", https=False):
# Is this the default key for everyone or should we parse it?
self._default_key = "cdc0cac1280b516e674f0057e4929bca84447cca8425007e33a88a5cf598a190"
self._login_password = ""
self._login_key = ""
self._cookies = {}
self._url = f"http://{host}"
self._url = f"https://{host}" if https else f"http://{host}"

def decode(self, data, key=""):
key = key or self._default_key
Expand All @@ -48,7 +48,7 @@ async def get(self, path, auth=False, referer=""):
referer = f"{self._url}/{referer}"
kwargs.update({"headers": {"Referer": referer}})
url += f"?_tn={await self._get_httoken(referer)}"
async with aiohttp.ClientSession() as session:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.get(url, **kwargs) as response:
_LOGGER.debug(f"GET - {url} - {response.status}")
key = self._login_key if auth else self._default_key
Expand All @@ -60,14 +60,14 @@ async def post(self, path, data, referer):
data.update({"httoken": await self._get_httoken(referer)})
data = "&".join([f"{k}={v}" for k, v in data.items()])
data = self.encode(data, key=self._login_key)
async with aiohttp.ClientSession() as session:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.post(url, cookies=self._cookies, headers={"Referer": referer}, data=data,
timeout=30) as response:
_LOGGER.debug(f"POST - {url} - {response.status}")
return self.decode(await response.text(), key=self._login_key)

async def _get_httoken(self, url):
async with aiohttp.ClientSession() as session:
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.get(url, cookies=self._cookies) as response:
_LOGGER.debug(f"GET - {url} - {response.status}")
return re.findall("_httoken = (\\d+)", await response.text())[0]
Expand All @@ -92,16 +92,15 @@ async def _get_login_key(self):

async def login(self, password):
self._login_password = password
if not self._login_key:
url = f"{self._url}/data/Login.json"
login_key = sha256(f"{await self._get_login_key()}:{password}".encode()).hexdigest()
data = self.encode("showpw=0&password=" + login_key)
async with aiohttp.ClientSession() as session:
async with session.post(url, data=data) as response:
_LOGGER.debug(f"POST - {url} - {response.status}")
if result := self.decode(await response.text())["login"] == "success":
self._cookies = response.cookies
return result
url = f"{self._url}/data/Login.json"
login_key = sha256(f"{await self._get_login_key()}:{password}".encode()).hexdigest()
data = self.encode("showpw=0&password=" + login_key)
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.post(url, data=data) as response:
_LOGGER.debug(f"POST - {url} - {response.status}")
if result := self.decode(await response.text())["login"] == "success":
self._cookies = response.cookies
return result

@property
async def status(self):
Expand Down

0 comments on commit 95c7ac3

Please sign in to comment.