Sindbad~EG File Manager

Current Path : /opt/dedrads/
Upload File :
Current File : //opt/dedrads/monarxctl

#!/usr/lib/rads/venv/bin/python3
from pathlib import Path
from platform import node, freedesktop_os_release
from shutil import rmtree
from urllib.request import urlretrieve
import argparse
import subprocess
import sys
import os
import rads

hostname = node()

monarx_repo = """[monarx]
name=Monarx Agent
baseurl=https://repository.monarx.com/repository/monarx-yum/linux/yum/el/{}/$basearch
gpgkey=
gpgcheck=0
"""
monarx_apt_repo = """deb [arch=amd64] https://repository.monarx.com/repository/ubuntu-{0}/ {0} main"""
apt_signing_key = """https://repository.monarx.com/repository/monarx/publickey/monarxpub.gpg"""

packages = [
    "monarx-agent",
    "monarx-protect",
    "monarx-cpanel-plugin",
    "monarx-whm-plugin",
]


parser = argparse.ArgumentParser(description='Install or remove monarx')

parser.add_argument(
    'function',
    nargs=1,
    default=None,
    help='function',
    choices=['install', 'remove'],
)
parser.add_argument('veid', type=int, nargs="?", default=None, help='VPS ID')
parser.add_argument(
    '--client_id', type=str, default='', help='Monarx client_id'
)
parser.add_argument(
    '--client_secret', type=str, default='', help='Monarx client_secret'
)


args = parser.parse_args()

if args.function is None:
    print("Please specify if you wish to install or remove monarx")
    sys.exit()

if args.veid is not None and not rads.vz.is_vz():
    print("You provided a VPS ID but this isnt a VZ node")
    sys.exit()

if args.function == ['install'] and (
    args.client_id == '' or args.client_secret == ''
):
    print(
        "Please provide client_id and client_secret from BitWarden for installation"
    )
    sys.exit()

monarx_conf = f"""client_id = {args.client_id}
client_secret = {args.client_secret}
user_base = /home/
tags = upsell
host_id = {hostname}"""

if rads.vz.is_vz():
    if args.veid is None:
        print("CTID is required (ex: monarxctl install $CTID)")
    else:
        ctid = str(args.veid)
        envid = rads.vz.get_envid(ctid)

    if not rads.vz.is_ct_running(ctid):
        print("container not found")
        sys.exit()


grep = ["grep", "--color=never", "-o", "[0-9]", "/etc/redhat-release"]
yum_cmd = ["yum", "-y", "-q"]
apt_cmd = ["apt-get", "-y"]
is_ubuntu = False
os_ver = ""


def check_install(veid):
    if is_ubuntu:
        distro_cmd = ["dpkg-query", "-W", "--showformat='${Status}'"]
    else:
        distro_cmd = ["rpm", "-q"]

    if veid is not None:
        pkg_cmd = vz_exec + distro_cmd + packages
    else:
        pkg_cmd = distro_cmd + packages
    try:
        pkg_out = subprocess.run(
            pkg_cmd, capture_output=True, check=True, text=True
        )
        if is_ubuntu and pkg_out:
            return True
        if "not installed" in pkg_out.stdout:
            return False
        return True
    except subprocess.CalledProcessError as e:
        if e.returncode in (1, 2):
            print(e.stderr)
        else:
            print(f"install check error: {e.cmd} returned {e.returncode}")
    return None


if args.veid:
    vz_exec = ["/usr/sbin/vzctl", "exec2", ctid]
    grep = vz_exec + grep
    yum_cmd = vz_exec + yum_cmd
    apt_cmd = vz_exec + apt_cmd
    path_prefix = '/vz/root/' + envid
else:
    ctid = None
    path_prefix = ""
try:
    print("Checking OS version..")
    if freedesktop_os_release().get('ID', '') == 'ubuntu':
        if ctid is not None:
            lsb_cmd = vz_exec + ["/usr/bin/lsb_release", "-sc"]
        else:
            lsb_cmd = ["/usr/bin/lsb_release", "-sc"]
        is_ubuntu = True
        check_cmd = "dpkg -l"
        # ensure apt/apt-get doesnt ask questions
        os.environ["DEBIAN_FRONTEND"] = "noninteractive"
        # these dont exist on ubuntu yet
        packages.remove("monarx-whm-plugin")
        packages.remove("monarx-cpanel-plugin")
        os_ver = subprocess.check_output(
            lsb_cmd, text=True, stderr=subprocess.DEVNULL
        )
    else:
        check_cmd = "rpm -q"
        os_ver = subprocess.check_output(
            grep, text=True, stderr=subprocess.DEVNULL
        )
        os_ver = int(os_ver.split('\n', maxsplit=1)[0])
        # dont install cpanel stuff if theres no cpanel
        if not os.path.exists("/usr/local/cpanel/"):
            packages.remove("monarx-whm-plugin")
            packages.remove("monarx-cpanel-plugin")
    print(f"Detected OS version: {os_ver}")
except subprocess.CalledProcessError as e:
    print(e.cmd, e.stderr)

if is_ubuntu:
    repo = Path(f'{path_prefix}/etc/apt/sources.list.d/monarx.list')
    apt_key_path = Path(f'{path_prefix}/etc/apt/trusted.gpg.d/monarx.asc')
    os_ver.strip('\n')
    repotext = monarx_apt_repo.format(os_ver.strip())
else:
    apt_key_path = None
    repo = Path(f'{path_prefix}/etc/yum.repos.d/monarx.repo')
    repotext = monarx_repo.format(os_ver)
conf = Path(f'{path_prefix}/etc/monarx-agent.conf')

print("repo file:", repo)
print("conf file:", conf)

if "install" in args.function:
    if check_install(ctid):
        print("Monarx packages appear to already be installed")
        sys.exit()

    # attempts to download key if its missing
    if is_ubuntu and not os.path.exists(apt_key_path):
        print("Fetching signing key...")
        try:
            urlretrieve(apt_signing_key, apt_key_path)
        except Exception as e:
            print(f"error downloading signing key: {e}")
            print(
                """you can download manually with:
wget -qO - https://repository.monarx.com/repository/monarx/publickey/monarxpub.gpg | sudo tee /etc/apt/trusted.gpg.d/monarx.asc"""
            )
            sys.exit()

    print("Beginning monarx install...")
    repo.write_text(repotext, encoding='ascii')
    conf.write_text(monarx_conf, encoding='ascii')
    try:
        if is_ubuntu:
            print("Updating package list with apt update...")
            if ctid is not None:
                update_cmd = vz_exec + [
                    "DEBIAN_FRONTEND=noninteractive",
                    "apt-get",
                    "-qq",
                    "update",
                ]
            else:
                update_cmd = ["apt-get", "-qq", "update"]
            try:
                subprocess.run(update_cmd, check=True)
            except subprocess.CalledProcessError as e:
                print(f"apt update failed: {e}")
                print("Please resolve any apt source issues and try again")
                sys.exit()
            apt_cmd.append("install")
            apt_inst = subprocess.check_output(
                apt_cmd + packages, stderr=subprocess.DEVNULL
            )
        else:
            yum_cmd.append("install")
            yum_inst = subprocess.check_output(
                yum_cmd + packages, stderr=subprocess.DEVNULL
            )
    except subprocess.CalledProcessError as e:
        print(f"install process error: {e.cmd}")
    if check_install(ctid):
        print("Monarx install complete.")
    else:
        print(
            f"""There may have been an issue with the installation process!!
              Please verify with: {check_cmd} {' '.join(packages)}"""
        )

if "remove" in args.function:
    if not check_install(ctid):
        print("Monarx packages not found - are you sure it's installed?")
        sys.exit()
    cleanup_files = [repo, conf]
    # removal will throw errors and leave this behind if the contents changed
    # the contents have obviously changed, it's a cache dir.
    print("Removing monarx-agent cache dir...")
    cache_path = Path(f'{path_prefix}/var/cache/monarx-agent/')
    if os.path.exists(cache_path):
        try:
            rmtree(cache_path)
        except PermissionError:
            print(f"permission error: unable to remove {cache_path}")
        except OSError as e:
            print(f"removal of {cache_path} failed: {e}")

    print("Removing monarx packages...")
    try:
        if is_ubuntu:
            apt_cmd.append("purge")
            apt_purge = subprocess.run(apt_cmd + packages, check=True)
            cleanup_files.append(apt_key_path)
        else:
            yum_cmd.append("remove")
            yum_inst = subprocess.run(yum_cmd + packages, check=True)
    except subprocess.CalledProcessError as e:
        print(f"package removal process error: {e.cmd}")
    print("Removing monarx repo and conf...")
    for file in cleanup_files:
        try:
            os.remove(file)
        except FileNotFoundError:
            pass
        except OSError as e:
            print(f"conf/repo removal error: {e.filename} - {e.strerror}.")

    if not check_install(ctid):
        print("Monarx removal complete.")
    else:
        print(
            """There may have been an issue with the removal process!!\n"""
            f"""Please verify with: {check_cmd} {' '.join(packages)}"""
        )

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists