Inital commit. Not working yet, just wanted to back it up.

This commit is contained in:
iRaven 2024-08-05 02:56:39 -05:00
commit 866c3d9339
3 changed files with 120 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
conf.json

7
conf-template.json Normal file
View File

@ -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"
}

112
main.py Normal file
View File

@ -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()])