2018-11-28 10:35:14 +01:00

157 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
import sys, os, platform, subprocess, re, argparse
platform_support = ['Linux']
html_dir_path = ""
logs_dir_path = ""
re_domain = r'^(?=.{1,253}$)(?!.*\.\..*)(?!\..*)([a-zA-Z0-9-]{,63}\.){,127}[a-zA-Z0-9-]{1,63}$'
def y_n_question(question_str):
yes = {'yes','y', 'ye', ''}
no = {'no','n'}
while True:
sys.stdout.write(question_str + " [Y/n]: ")
choice = input().lower()
if choice in yes:
return True
elif choice in no:
return False
else:
sys.stdout.write("\nPlease respond with 'yes' or 'no'\n")
continue
def sanity_check_system():
# check platform
if platform.system() not in platform_support:
sys.exit("Platform " + platform.system() + " not supported. Aborting...")
# check apache2
r = subprocess.call("apache2 -v", shell=True) == 0
# check apache2 (ubuntu-style)
u = os.path.exists('/etc/apache2/sites-available/')
if not r and u:
sys.exit("Apache2 (ubuntu-style) not installed on your system. Aborting...")
def sanity_chek_platform():
global html_dir_path, logs_dir_path
usr = os.getlogin()
html_dir_path = os.path.join('/home', usr, 'html')
logs_dir_path = os.path.join('/home', usr, 'logs')
if not os.path.exists(html_dir_path):
if y_n_question("Path - " + html_dir_path + ' - does not exists. Create it?'):
os.makedirs(html_dir_path)
else:
sys.exit("Can not configure platform. Aborting...")
if not os.path.exists(logs_dir_path):
if y_n_question("Path - " + logs_dir_path + ' - does not exists. Create it?'):
os.makedirs(logs_dir_path)
else:
sys.exit("Can not configure platform. Aborting...")
def vhost_add(domain):
global html_dir_path, logs_dir_path, re_domain
print(" adding vhost domain — " + domain)
if re.match(re_domain, domain) is None:
print("Invalid domain name: " + domain + " -> pass")
www = os.path.join(html_dir_path, domain)
os.makedirs(www, exist_ok=True)
logs = os.path.join(logs_dir_path, domain)
os.makedirs(logs, exist_ok=True)
# debug: this file might not be here
with open('vhost_tmpl') as vhost_tmpl_fp:
vhost_tmpl = vhost_tmpl_fp.read()
usr = os.getlogin()
vhost = vhost_tmpl.replace("%domain?", domain).replace("%user?", usr)
# debug: write file directly to '/etc/apache2/sites-available/' ?
vhost_file = os.path.join(www, domain + '.conf')
with open(vhost_file, 'w+') as vhost_file_fp:
vhost_file_fp.write(vhost)
bla = os.path.join(www, 'itworks.txt')
with open(bla, 'w+') as bla_fp:
bla.write("it does.")
# check is ssl cert exists
cert = os.path.join('/etc/letsencrypt/live', domain)
if not os.path.exists(cert):
print(" warning: SSL certificates do not exist for domain - " + domain)
print(" warning: Please make sure to place them in " + cert + " to allow secure https connection to your site.")
# mv conf file to apache
if y_n_question("Move " + vhost_file + " to /etc/apache2/sites-available/ ?"):
vhost_conf_file = os.path.join('/etc/apache2/sites-available/', domain + '.conf')
subprocess.call(['sudo', 'mv', vhost_file, vhost_conf_file])
def vhost_remove(domain):
print(" removing domain — " + domain)
vhost_conf_file = os.path.join('/etc/apache2/sites-available/', domain + '.conf')
if os.path.exists(vhost_conf_file):
if y_n_question("Delete " + vhost_conf_file + " ?"):
subprocess.call(['sudo', 'rm', vhost_conf_file])
www = os.path.join(html_dir_path, domain)
if os.path.exists(www):
if y_n_question("Delete " + www + " ?"):
subprocess.call(['sudo', 'rm', '-r', www])
logs = os.path.join(logs_dir_path, domain)
if os.path.exists(logs):
if y_n_question("Delete " + logs + " ?"):
subprocess.call(['sudo', 'rm', '-r', logs])
if __name__ == "__main__":
p = argparse.ArgumentParser(description='vhost helper')
p.add_argument('domain', metavar="domain", help="vhost domain(s)", nargs="+")
g = p.add_mutually_exclusive_group()
g.add_argument('-a', '--add', action='store_true', help="adds vhost for given domain(s)")
g.add_argument('-r', '--remove', action='store_true', help="removes vhost for given domain(s)")
args = p.parse_args()
print('1. sanity checks')
sanity_check_system()
sanity_chek_platform()
print('2. vhosting')
for d in args.domain:
if args.add:
vhost_add(d)
elif args.remove:
vhost_remove(d)
if y_n_question("Restart apache2?"):
subprocess.call(['sudo', 'service', 'apache2', 'restart'])
print('done.')