import os import json import logging import requests import re from ipaddress import ip_address # Open the config file and make it accessible via "cfg" with open("conf.json", "r") as file: cfg = json.load(file) # Configure logging logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s') log = logging.getLogger() try: if cfg["loglevel"] == "debug": log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) except KeyError: log.setLevel(logging.INFO) log.debug("Logger was initialized") ## Functions def checkIfIP(host): try: ip_address(host) log.debug(str(host) + " is an IP address") return True except: log.debug(host + " is not an IP address.") return False def loginToNPM(apiurl, user, pw): # To retrieve NPM's API session token # Returns the token used for API requests. session = requests.Session() url = apiurl + "/api/tokens" loginreq = session.post(url,data={"identity": user, "secret": pw}) if loginreq.status_code == 200: # Check if the API accepted our creds. log.info("Logged into Nginx Proxy Manager") response = loginreq.json() return response['token'] elif loginreq.status_code == 401: log.error("Your Nginx Proxy Manager credentials are incorrect. Please verify you put in the right ones!") exit() else: log.error("Nginx Proxy Manager: " + response['error']['message']) return None def loginToPihole(serveraddr, phpassword, session): # NEW Method as of Pi-Hole version 6.0 and newer. # I truly appreciate them fixing but this broke so many things. apiurl = "http://" + serveraddr + "/api/auth" passwordjson = {"password": phpassword} loginrq = session.request("POST", apiurl, json=passwordjson, verify=False) log.debug("Sent POST for getting Pi-hole API authorization.") if loginrq.status_code == 200: # yay log.debug("API returned a 200, proceeding.") # We're good c: log.info("Logged into Pi-hole API on "+serveraddr+"!") fullresponse = loginrq.json() phpsessid = fullresponse["session"]["sid"] token = fullresponse["session"]["csrf"] log.debug("phpsessid: " + phpsessid + " Token: "+ token) return {'phpsessid': phpsessid, "csrftoken": token} elif loginrq.status_code == 401: # Unauthorized log.debug("Pi-hole returned a 401, halting!") log.error("The Pi-hole retured an unauthorized error!") log.error("Please make sure your Pi-hole password in conf.json is correct and accurate.") return None else: log.error("Pi-hole returned this " + str(apireq.status_code) + " in error: "+ apireq.text) def loginToPiholeOld(apiurl, phpassword): # For whatever reason, Pi-hole's web CSRF token is in a hidden
element returned by the login.php in the homepage right after you login. # This took *WAY* too long to figure out. This should be in the header for ease-of-use. session = requests.Session() url = "http://" + apiurl + "/admin/login.php" loginrq = session.post(url,data={"pw": phpassword}) phpsessid = (str(loginrq.cookies.get_dict()["PHPSESSID"])) regex = r'(