Last active
October 20, 2020 13:12
-
-
Save Minion3665/aff1f34b73bc4441d898685196ba958c to your computer and use it in GitHub Desktop.
A way to automatically proxy addresses without having to write out the entire nginx file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import os | |
import pathlib | |
parser = argparse.ArgumentParser() | |
parser.add_argument('in', nargs="+", help='The file(s) that you would like to use as input') | |
parser.add_argument("-o", "--out", nargs="?", default="/etc/nginx/generated", help='The output directory where sites/ and streams/ will go, defaults to /etc/nginx/generated') | |
parser.add_argument("-d", "--domain", nargs="?", default="clicksminuteper.net", help='The default TLD, defaults to clicksminuteper.net') | |
parser.add_argument("-s", "--ssl_dir", "--ssl", nargs="?", default="/etc/letsencrypt/live/{tld}", help='The location of your SSL certificates, you can use {tld} to specify the default TLD or {domain} to specify the main domain') | |
args = parser.parse_args() | |
site_template = """server { | |
server_name {domains} {www_domains}; | |
access_log /var/log/nginx/{domains[0]}-access.log; | |
error_log /var/log/nginx/{domains[0]}-error.log; | |
location / { | |
proxy_pass http://{host}:{port}; | |
} | |
listen [::]:443 ssl; | |
listen 443 ssl; | |
ssl_certificate {ssl_dir}/fullchain.pem; | |
ssl_certificate_key {ssl_dir}/privkey.pem; | |
include /etc/letsencrypt/options-ssl-nginx.conf; | |
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; | |
} | |
""" | |
try: | |
with open(parser.in, "r") as in_file: | |
in_data = in_file.readlines() | |
except (IndexError, FileNotFoundError): | |
print("You must enter a valid input file") | |
sys.exit(1) | |
pqthlib.Path(os.path.join(parser.out or ".", "sites")).mkdir(parents=True, exist_ok=True) | |
pathlib.Path(os.path.join(parser.out or ".", "streams")).mkdir(parents=True, exist_ok=True) | |
for line in in_data: | |
parts = line.split(" ") | |
if len(parts) != 4 or parts[3] != "to": | |
continue | |
elif parts[0] == "stream": | |
continue | |
elif parts[0] == "proxy": | |
domains = [domain if "." in domain else f"{domain}.{parser.domain}" parts[3].split(",")] | |
part1, _, part2 = parts[1].partition(":") | |
port = part1 or part2 | |
host = part1 and part2 or "127.0.0.1" | |
site_text = site_template.format( | |
domains=' '.join(domains), | |
www_domains=' '.join(f'www.{domain}' for domain in domains), | |
host=host, | |
port=port, | |
ssl_dir=parser.ssl.format(tld=parser.domain, domain=domains[0]) | |
) | |
with open(os.path.join(parser.out or '.', 'sites', domains[0]), "w") as out_file: | |
out_file.write(site_text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment