Mini Shell

Direktori : /proc/self/root/proc/thread-self/root/proc/thread-self/root/opt/sharedrads/
Upload File :
Current File : //proc/self/root/proc/thread-self/root/proc/thread-self/root/opt/sharedrads/suspend_domain

#!/opt/imh-python/bin/python3
"""IMH/HUB ShareRADs - suspend_domain.py"""
# Writen by Michael B michaelb@inmotionhostin.com

import sys
import pwd
import syslog
from argparse import ArgumentParser
from pathlib import Path
import os
import time
from cpapis import whmapi1

LOG_FILE = '/var/log/suspension.log'


def logdate():
    """Format date for suspension log"""
    return time.strftime("%Y-%m-%d:%H:%M:%S %Z", time.localtime(time.time()))


def log_suspension(domain, susp_type, comment):
    """Log domain suspension"""
    procname = os.path.basename(sys.argv[0])
    sudo_user = os.getenv("SUDO_USER")
    blame = get_calling_username()
    entry = 'Domain: {} [{}] {}: "{}"'.format(
        domain, susp_type.upper(), blame, comment or '-'
    )
    syslog.openlog(procname)
    syslog.syslog(entry)
    with open(LOG_FILE, 'a', encoding='utf-8') as log_f:
        log_f.write(f'{logdate()} {sudo_user}: {entry}\n')


def get_calling_username():
    """Get username which ran this script"""
    try:
        blame = '{}:{}'.format(
            os.getlogin(), pwd.getpwuid(os.geteuid()).pw_name
        )
    except OSError:
        blame = pwd.getpwuid(os.geteuid()).pw_name
    return blame


def suspend_domain(docroot: str, domain: str):
    """Suspend a domain via .htaccess"""
    path = os.path.join(docroot, '.htaccess')

    if os.path.isfile(path):
        os.rename(path, '%s.suspended' % path)
        print(".htaccess found. Moving and placing suspension .htaccess")
    else:
        Path(path + ".suspended").touch(mode=0o644)

    with open(path, 'w', encoding='utf-8') as hta_f:
        hta_f.write("RedirectMatch .* http://%s/unavailable.html\n" % domain)

    log_suspension(domain, "suspended", 'via suspend_domain')

    print("Domain %s has been suspended." % domain)


def unsuspend_domain(docroot: str, domain: str):
    """Unsuspend a domain via .htaccess"""
    path = os.path.join(docroot, '.htaccess')

    if os.path.isfile(path + ".suspended"):
        os.remove(path)
        os.rename(path + ".suspended", path)
        log_suspension(domain, "unsuspended", 'via suspend_domain')
    else:
        print("Domain %s doesn't appear to be suspended" % domain)

    print("Domain  %s has been unsuspended" % domain)


def parse_args() -> tuple[bool, list[str]]:
    parser = ArgumentParser(description=__doc__)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        "-s", "--suspend", nargs='+', help="Suspends the domain listed"
    )
    group.add_argument(
        "-u", "--unsuspend", nargs='+', help="Unsuspends the domain specified"
    )
    args = parser.parse_args()
    if args.suspend:
        return True, args.suspend
    return False, args.unsuspend


def main():
    """Main logic of suspend_domain"""
    suspend, domains = parse_args()
    rcode = 0
    for domain in domains:
        try:
            api = whmapi1('domainuserdata', {'domain': domain}, check=True)
            domainroot = api['data']['userdata']['documentroot']
        except Exception as exc:
            print(exc, file=sys.stderr)
            print(
                f'Unable to get documentroot for {domain} from whmapi1',
                file=sys.stderr,
            )
            rcode = 2
            continue
        if suspend:
            suspend_domain(domainroot, domain)
        else:
            unsuspend_domain(domainroot, domain)
    sys.exit(rcode)


if __name__ == '__main__':
    main()

Zerion Mini Shell 1.0