From 866c3d93399a263042f9f7b1b6e85cf29383f266 Mon Sep 17 00:00:00 2001 From: iRaven4522 Date: Mon, 5 Aug 2024 02:56:39 -0500 Subject: [PATCH] Inital commit. Not working yet, just wanted to back it up. --- .gitignore | 1 + conf-template.json | 7 +++ main.py | 112 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 .gitignore create mode 100644 conf-template.json create mode 100644 main.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..85825a5 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +conf.json diff --git a/conf-template.json b/conf-template.json new file mode 100644 index 0000000..16fbbf2 --- /dev/null +++ b/conf-template.json @@ -0,0 +1,7 @@ +{ + "loglevel": "debug", + "npmapi": "https://npm.corp.iraven.net", + "npmkey": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhcGkiLCJzY29wZSI6WyJ1c2VyIl0sImF0dHJzIjp7ImlkIjoxfSwiZXhwaXJlc0luIjoiMWQiLCJqdGkiOiJaT0IrNmV6WkRVVHR0RW9SIiwiaWF0IjoxNzIyODMyMjU2LCJleHAiOjE3MjI5MTg2NTZ9.utpeUVqOWSq1N2qXTsjjMjmvIenTFkLvQTsYPSFMAwK7v2U8XJgDhuQaqaas0Tv1tVpAuVK8LpJC7WQUPE1TkOzQormp5tb7EqGvQy4jRQRZ5q6xkUuE_KW2ME5M4rboy1cjANNiWeRMhCpkWBg4JreFYd0-vWZIQf-3LnkXux-rcaWyRvDsWoB3xkNXvQLnuTIREAAH3CuGkFpbsJD8AjMN8ciYofWP8ZaE9zzbPDMFQ84mXRhpmmQVgorWC9JlGEzz_-AYUrq-bB5v03tHeqVfWvFtmVlfUpObUlDIDQr2MBGXHErIPa8d9amqqZLHSbo7D96QsFMrfavLn9TBRg", + "piholeapi": "https://pihole.corp.iraven.net", + "piholekey": "balls" +} diff --git a/main.py b/main.py new file mode 100644 index 0000000..c33add0 --- /dev/null +++ b/main.py @@ -0,0 +1,112 @@ +import os +import json +import logging +import requests +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) + logging.debug(str(host) + " is an IP address") + return True + except: + logging.debug(host + " is not an IP address.") + return False + +def getNPMHosts(apiurl,apikey,type): + log.debug("Type is set to "+str(type)+".") + if type == "proxy": + log.info("Retrieving proxy hosts from NPM API...") + url = apiurl + '/api/nginx/proxy-hosts' + logging.debug("Set hosts API URL to " + url + ".") + elif type == "redir": + log.info("Retrieving redirection hosts from NPM API...") + url = apiurl + '/api/nginx/redirection-hosts' + logging.debug("Set hosts API URL to " + url + ".") + elif type == "404" or type == "dead": + log.info("Retrieving 404 (dead) hosts from NPM API...") + url = apiurl + '/api/nginx/dead-hosts' + logging.debug("Set hosts API URL to " + url + ".") + else: + log.error("No type of hosts to retrieve from NPM was specified.") + return None + hostlist = [] # Make the list. + # url = apiurl + '/api/nginx/proxy-hosts' + # logging.debug("Set hosts API URL to " + url + ".") + apireq = requests.get(url, headers={'Authorization': apikey}) + if apireq.headers['content-type'] == "application/json; charset=utf-8": # Check if the API shat us a JSON. + logging.debug("Passed content-type = application/json check.") + logging.debug("HTTP Status Code: "+ str(apireq.status_code)) + if apireq.status_code == 200: # Check if the API returned a 200 and accepted our token/key. + logging.debug("API returned a 200, proceeding.") # We're good c: + fullresponse = apireq.json() + for i in range(len(fullresponse)): + logging.debug("Adding indice " + str(i) + " to list, containing "+ str(fullresponse[i]['domain_names'])) + hostlist = hostlist + fullresponse[i]['domain_names'] + logging.debug("List has been created.") + for h in range(len(hostlist)): + if checkIfIP(hostlist[h]): + logging.debug("Deleting IP address "+ hostlist[h] + " from the list of hosts.") + hostlist.pop(h) + break # Temp fix!! + return hostlist + elif apireq.status_code == 403: # If the API gave us a 403 Forbidden/Permission Denied + logging.debug("API returned a 403, halting!") + logging.error("The API retured a permission denied error!") + logging.error("Please make sure your Nginx Proxy Manager API key in conf.json is correct and accurate.") + return None + else: + logging.error("The API returned a " + str(apireq.status_code)+".") + logging.error("Please make sure your Nginx Proxy Manager API key or URL in conf.json is correct and accurate.") + return None + else: # If we don't get a JSON + logging.error("The API did not return a JSON, and instead a content type of "+str(apireq.headers['content-type'])+".") + logging.error("Please make sure your Nginx Proxy Manager API key or URL in conf.json is correct and accurate.") + return None + +def addPiHoleHosts(apiurl, apikey,targetsvr, list): + url = apiurl + "/scripts/pi-hole/php/customcname.php" + for i in list: + payload = "action=add&domain="+list[i]+"&target="+targetsvr+"&token="+apikey + apireq = requests.post(url,data=payload) + if apireq.status_code == 200: # Check if the API returned a 200 and accepted our token/key. + response = apireq.json() + if response['success'] == "false": + log.debug("Pi-Hole API returned false!") + log.warning("The Pi-Hole API gave the following message:"+ response['message']) + elif response['success'] == "true": + logging.debug("PiHole API returned true. Message returned: "+ response['message']) + else: + + +log.debug("Script has started!") +proxyhosts = getNPMHosts(cfg['npmapi'],cfg['npmkey'],"proxy") # Get Proxy Hosts +redirhosts = getNPMHosts(cfg['npmapi'],cfg['npmkey'],"redir") # Get Redir Hosts +deadhosts = getNPMHosts(cfg['npmapi'],cfg['npmkey'],"dead") # Get 404 Hosts +log.debug("Adding all the hosts together") +allhosts = proxyhosts + redirhosts +if cfg['removedead'] == False: # if "removedead" in the config is true, add the dead hosts to the main list, but otherwise no. + allhosts = allhosts + deadhosts +else: + removePiHoleHosts(cfg["piholeapi"],cfg["piholekey"],deadhosts) +print(allhosts) +import random +print(allhosts[random.randint()]) \ No newline at end of file