Skip to content

Commit

Permalink
Improve logging, add SYSTEM install type
Browse files Browse the repository at this point in the history
  • Loading branch information
logandhillon committed Jul 25, 2024
1 parent ff8978f commit 37a2fb6
Showing 1 changed file with 92 additions and 40 deletions.
132 changes: 92 additions & 40 deletions install.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import sys
import subprocess
from enum import Enum

PYREQS_URL = "https://raw.githubusercontent.com/badtechnologies/bdsh/main/requirements.txt"
GIT_URL = "https://github.com/badtechnologies/bdsh"
Expand All @@ -16,15 +17,27 @@
BDSH_ROOT = "bdsh"


class InstallType(Enum):
STANDARD = "std" # standard bdsh installation
SYSTEM = "sys" # system-wide bdsh installation; made for BadOS Shell System

def display():
for install_type in InstallType:
print(f"\t> {install_type.value} ({install_type.name})")


# default args
install_type = InstallType.STANDARD


def install_package(package_name: str):
package_name = package_name.strip()
try:
print(f"\nInstalling '{package_name}'")
subprocess.check_call(
[sys.executable, "-m", "pip", "install", package_name])
print(f"Python package '{package_name}' installed successfully")
except subprocess.CalledProcessError as e:
print(f"Failed to install Python package '{package_name}': {e}")
subprocess.check_call([sys.executable, "-m", "pip", "install", package_name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("OK")
except subprocess.CalledProcessError:
print("FAILED")
exit(0x81)


def prompt(prompt: str, on_cancel: callable, **default: str):
Expand All @@ -38,47 +51,66 @@ def print_header(header: str):
print('\n'+(f" {header} ").center(50, '='))


def print_task(task: str):
print(task+'...', end=" ", flush=True)


if __name__ == "__main__":
print("BDSH INSTALLATION TOOL\n(c) Bad Technologies\n")
if os.path.exists(BDSH_ROOT):
# parse args
for arg in sys.argv:
arg = arg.split("=")
if len(arg) < 1:
continue
if arg[0] == "type":
try:
install_type = InstallType(arg[1])
except ValueError as e:
print(f"{e}, choose from:")
InstallType.display()
exit()

print(f"BDSH INSTALLATION TOOL, {install_type.name} INSTALL\n(c) Bad Technologies\n")
if install_type is not InstallType.SYSTEM and os.path.exists(BDSH_ROOT):
prompt("This will replace your current bdsh configs, proceed?", lambda: exit(0))

print_header("SETUP ENV")

if 'VIRTUAL_ENV' not in os.environ:
prompt("This will install bdsh-required Python packages to your current env. Continue?", lambda: exit(0))

print("Upgrading pip...")
print_task("Upgrading environment package installer")
try:
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
except subprocess.CalledProcessError as e:
print(f"Failed to upgrade pip: {e}")
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("OK")
except subprocess.CalledProcessError:
print("FAILED")

print_task("Installing system HTTP client")
install_package("requests")
import requests

if os.path.exists(PYREQS):
print("Package list already download, skipping")
else:
print(f"\nDownloading package list...")
print_task(f"Downloading package list")

res = requests.get(PYREQS_URL)

if not res.ok:
print(f"Failed to fetch package list, please download it manually from the bdsh repo: {GIT_URL}")
exit(0)
print("FAILED")
if install_type is not InstallType.SYSTEM:
print(f"Please download 'requirements.txt' manually from the bdsh repo: {GIT_URL}")
exit(0x82)

with open(PYREQS, 'wb') as f:
f.write(res.content)
print(f"Downloaded package list.")
print(f"OK")

print("\nInstalling packages...")
with open(PYREQS, 'r') as f:
for line in f.readlines():
install_package(line)
lines = f.readlines()
pkgs = len(lines)
for i, pkg in enumerate(lines, 1):
print_task(f"Installing system packages ({i}/{pkgs})")
install_package(pkg)

print("\nCleaning up...")
print("\nCleaning up")
os.remove(PYREQS)

# IMPORT STATEMENTS (AFTER INSTALLING PIP PACKAGES)
Expand All @@ -89,21 +121,25 @@ def print_header(header: str):
if os.path.exists(BDSH_SRC):
print("bdsh source already downloaded, skipping")
else:
print_task("Downloading bdsh source")
res = requests.get(BDSH_SRC_URL)

if not res.ok:
print(f"Failed to fetch bdsh source, please download it manually from the bdsh repo: {GIT_URL}")
exit(0)
print("FAILED")
if install_type is not InstallType.SYSTEM:
print(f"Please download 'bdsh.py' manually from the bdsh repo: {GIT_URL}")
exit(0x83)

with open(BDSH_SRC, 'wb') as f:
f.write(res.content)

print("Downloaded bdsh source successfully")
print("OK")

import bdsh

print_header("INIT BDSH")

print_task("Initializing bdsh directory structure")
try:
if not os.path.exists(BDSH_ROOT):
os.mkdir(BDSH_ROOT)
Expand All @@ -112,11 +148,14 @@ def print_header(header: str):
path = os.path.join(BDSH_ROOT, dir)
if not os.path.exists(path):
os.mkdir(path)

print("OK")
except Exception as e:
print(f"Error initializing bdsh directory structure: {e}")
exit(-1)
print(f"FAILED\n{e}")
exit(0x84)

print(f"Populated bdsh root ({BDSH_ROOT}/) successfully")
if install_type is not InstallType.SYSTEM:
print(f"Populated bdsh root ({BDSH_ROOT}/) successfully")

print("Starting virtual bdsh session")
virtsh = bdsh.Shell(sys.stdout, sys.stdin)
Expand Down Expand Up @@ -162,26 +201,28 @@ def exitloop():

install_packages = True
while install_packages:
print_task("Fetching bpm from bpl")
res = requests.get(f'{BPL_URL}/bpm/bpl.json')

if not res.ok:
print(f"""Something went wrong while fetching bpm from bpl, more information below:
print(f"""FAILED\nSomething went wrong while fetching bpm from bpl, more information below:
\tError:\t\tHTTP {res.status_code} {res.reason}
\tLibrary:\t{BPL_URL}
\tResponse:\t{res.content.decode()}""")

prompt("Try again?", lambda: globals().update(install_packages=False))
else:
print("OK")
break

if install_packages:
meta = res.json()
print(f"Installing bpm-{meta['version']} ({meta['name']})")
print_task(f"Installing bpm-{meta['version']} ({meta['name']})")
res = requests.get(f'{BPL_URL}/bpm/{meta["bin"]}')

while install_packages:
if not res.ok:
print(f"""Something went wrong while downloading bpm binaries, more information below:
print(f"""FAILED\nSomething went wrong while downloading bpm binaries, more information below:
\tError:\t\tHTTP {res.status_code} {res.reason}
\tLibrary:\t{BPL_URL}
\tResponse:\t{res.content.decode()}
Expand All @@ -196,7 +237,7 @@ def exitloop():
with open(virtsh.get_path('exec', 'bpm'), 'wb') as f:
f.write(res.content)

print(f"Installation complete: bpm is installed")
print("OK")

print_header("INSTALL PACKAGES")

Expand All @@ -211,7 +252,7 @@ def exitloop():
key.write_private_key_file(virtsh.get_path('cfg', 'badbandssh_rsa_key'))
print("Stored BadBandSSH private key")

print_header("CREATE LAUNCHER SCRIPTS")
print_header("CREATE LAUNCHER")
if not os.path.exists("bin"):
os.mkdir("bin")

Expand All @@ -220,17 +261,28 @@ def exitloop():
if sys.platform.startswith("win"):
with open(os.path.join("bin", "bdsh.bat"), "w") as f:
f.write(f'@echo off\n{sys.executable} {binpath} %*')
print("Created WINDOWS launcher script")
print("Created WINDOWS launcher")

else:
with open(os.path.join("bin", "bdsh"), "w") as f:
f.write(f'#!/bin/bash\n{sys.executable} {binpath} "$@"')
os.chmod(os.path.join("bin", "bdsh"), 0o755)
print("Created UNIX launcher script")
if install_type is not InstallType.SYSTEM:
print("Created UNIX launcher")
else:
print("Created launcher")

print(f"[!] Please add the following path to your PATH after installation completes:\n\t{os.path.abspath('bin')}")
getpass("Press ENTER to continue...")
if install_type is not InstallType.SYSTEM:
print(f"[!] Please add the following path to your PATH after installation completes:\n\t{os.path.abspath('bin')}")
getpass("Press ENTER to continue...")

print_header("CLEANING UP")

print("Done!")
print("Done!\n")

if install_type is not InstallType.SYSTEM:
print(f"""After adding the bdsh binaries to PATH, you can run bdsh with:
bdsh
Or, run the binary directly by running this file:
{os.path.join(os.path.abspath('bin'), "bdsh.bat" if sys.platform.startswith("win") else "bdsh")}""")

0 comments on commit 37a2fb6

Please sign in to comment.