44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
import sys
|
|
import urllib.request as urllib2
|
|
import urllib.parse as urlparse
|
|
import ssl
|
|
|
|
BASEURL = 'https://fhem.auwiesen2.de/fhem?'
|
|
url = BASEURL + 'detail=WEB'
|
|
|
|
def get_token(url):
|
|
# Split the URL to extract the username and password
|
|
nurl = urlparse.urlsplit(url)
|
|
username = nurl.username
|
|
password = nurl.password
|
|
|
|
# Reconstruct the URL without the username and password
|
|
url = url.replace(f"{username}:{password}@", '')
|
|
url = url.replace(" ", "%20")
|
|
|
|
# Create an unverified HTTPS context (not recommended for production)
|
|
ssl._create_default_https_context = ssl._create_unverified_context
|
|
|
|
# Setup HTTP Basic Authentication
|
|
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
|
|
password_mgr.add_password(None, url, username, password)
|
|
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
|
|
opener = urllib2.build_opener(handler)
|
|
urllib2.install_opener(opener)
|
|
|
|
try:
|
|
# Send the request and retrieve the response
|
|
with urllib2.urlopen(url, data=None, timeout=10) as uu:
|
|
token = uu.read().decode('utf-8')
|
|
# Extract the CSRF token
|
|
token = token[token.find('csrf_'):]
|
|
token = token[:token.find("'")]
|
|
return token
|
|
except urllib2.URLError as e:
|
|
print(f'URLError: {e.reason}')
|
|
return False
|
|
|
|
# Example usage
|
|
token = get_token(url)
|
|
print(f"Token: {token}")
|