Mini Shell

Direktori : /opt/sharedrads/
Upload File :
Current File : //opt/sharedrads/reset_cpanel

#!/opt/imh-python/bin/python3
"""Resets cPanel passwords"""
import sys
from cpapis import whmapi1
import os
import random
import string
from rads import color, setup_logging, is_cpuser, get_owner, get_login
from pathlib import Path
import argparse

import pp_api
import logging
from platform import node


def api_success(json_response):
    """deprecated"""
    try:
        return int(json_response['status']) == 1
    except (TypeError, KeyError, ValueError):
        pass
    try:
        return int(json_response['metadata']['result']) == 1
    except (TypeError, KeyError, ValueError):
        pass
    try:
        return int(json_response['result']['status']) == 1
    except (TypeError, KeyError, ValueError):
        try:
            return int(json_response['result'][0]['status']) == 1
        except (TypeError, IndexError, KeyError, ValueError):
            pass
    return False


def get_args():
    """Parse users and message from commandline, or prompt for them"""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '-u',
        '--user',
        type=str,
        dest='users',
        nargs='*',
        default=[],
        help='user to reset password for',
    )
    parser.add_argument(
        '-m', '--message', type=str, help='reason for the password reset'
    )
    raw = parser.parse_known_args()
    results = raw[0]
    if raw[1] != []:
        results.users = raw[1]
    if not results.message:
        sys.exit('Use the -m flag to add a message')
    if len(results.users) == 0:
        sys.exit("No users specified")
    else:
        for user in results.users:
            if not is_cpuser(user):
                sys.exit(f'{user} is not a valid cpanel user')
    return results


def reset_users_from_list(user_list, message):
    """loop through user_list and reset passwords"""
    length = 13
    chars = '{0.ascii_letters}{0.digits}!@#$%^&*()'.format(string)
    for editinguser in user_list:
        random.seed = os.urandom(1024)
        acceptable_pass = False
        while acceptable_pass is False:
            newpass = ''.join(random.choice(chars) for i in range(length))
            if newpass[0] != '@':
                acceptable_pass = True
        print(
            "Attempting to reset password for {} to {}: ".format(
                editinguser, color.yellow(newpass)
            ),
            end=' ',
        )
        if api_success(
            whmapi1('passwd', {"user": editinguser, "password": newpass})
        ):
            print(color.green('success'))
            if 'inmotionhosting' in node() or 'servconfig' in node():
                eid = 615
            elif 'webhostinghub' in node():
                eid = 616
            else:
                print(node())
                sys.exit('Cannot find brand to send email. Check the hostname.')
            message = {
                'subject': "cPanel Password Reset",
                'eid': eid,
                'var1': message,
                'var2': None,
            }
            mail_user(message, editinguser)
        else:
            print(color.red('FAILED'))

        sessions = Path(f"/var/cpanel/sessions/")

        for file in (sessions / "raw").glob(f"{editinguser}:*"):
            file.unlink()
        
        for file in (sessions / "cache").glob(f"{editinguser}:*"):
            file.unlink()


def mail_user(message_id, cpuser):
    """This part sends the message to the user.
    Reference for pp_api emails"""

    reseller = None
    try:
        reseller = (
            cpuser in whmapi1("listresellers", check=True)['data']['reseller']
        )
    except Exception as exc:
        sys.exit(f"Unable to enumerate resellers: {exc}")
    if 'servconfig' in node() and not reseller:
        child = cpuser
        cpuser = get_owner(cpuser)
        message_id['eid'] = 620
        message_id['var2'] = message_id['var1']
        message_id['var1'] = child

    if 'servconfig' in node() and (not reseller or get_owner(cpuser) is None):
        sys.exit('Unable to determine owner of that user')

    pp_connect = pp_api.PowerPanel()
    template_id = int(message_id['eid'])
    data = {
        'template': template_id,
        'cpanelUser': cpuser,
        'variable_1': message_id['var1'],
        'variable_2': message_id['var2'],
        'variable_3': None,
    }

    results = pp_connect.call("notification.send", **data)
    if not hasattr(results, 'status') or results.status != 0:
        log_error = f"Failed to send notification to {cpuser}"
        print(color.red('FAILED'), end=' ')
        if hasattr(results, 'message'):
            print(results.message)
        logging.error(log_error)

    else:
        whoami = get_login()
        log_success = "Success: {} sent to {} by {}".format(
            message_id['subject'], cpuser, whoami
        )
        logging.info(log_success)
        print("message Sent Successfully")


def main():
    """Main function: setup loging, obtain args, reset passwords"""
    setup_logging(
        path='/var/log/suspension.log', loglevel=logging.INFO, print_out=False
    )
    results = get_args()
    reset_users_from_list(results.users, results.message)


if __name__ == "__main__":
    main()

Zerion Mini Shell 1.0