From e633965a1a9e1de5ed502497ddbca37e311f64b7 Mon Sep 17 00:00:00 2001 From: Marcel Schwarz Date: Sun, 2 Aug 2020 00:55:48 +0200 Subject: [PATCH 01/10] Remove classes from easy modules * bashrc * hacker * helloworld * installer * update * teamspeak --- main.py | 28 ++++++------- modules/bashrc/BashrcModule.py | 26 ------------ modules/bashrc/__init__.py | 31 ++++++++++++++ .../{Fail2BanModule.py => __init__.py} | 5 +++ modules/hacker/Hacker.py | 29 -------------- modules/hacker/__init__.py | 34 ++++++++++++++++ modules/helloworld/HelloWorld.py | 13 ------ modules/helloworld/__init__.py | 16 ++++++++ modules/install/ToolsInstaller.py | 22 ---------- modules/install/__init__.py | 29 ++++++++++++++ modules/systemupdate/Systemupdate.py | 13 ------ modules/systemupdate/__init__.py | 16 ++++++++ modules/teamspeak/Teamspeak.py | 32 --------------- modules/teamspeak/__init__.py | 40 +++++++++++++++++++ 14 files changed, 185 insertions(+), 149 deletions(-) delete mode 100644 modules/bashrc/BashrcModule.py create mode 100644 modules/bashrc/__init__.py rename modules/fail2ban/{Fail2BanModule.py => __init__.py} (94%) delete mode 100644 modules/hacker/Hacker.py create mode 100644 modules/hacker/__init__.py delete mode 100644 modules/helloworld/HelloWorld.py delete mode 100644 modules/install/ToolsInstaller.py delete mode 100644 modules/systemupdate/Systemupdate.py delete mode 100644 modules/teamspeak/Teamspeak.py create mode 100644 modules/teamspeak/__init__.py diff --git a/main.py b/main.py index aedb96f..41c80e8 100644 --- a/main.py +++ b/main.py @@ -1,25 +1,25 @@ import fire -from modules.helloworld.HelloWorld import HelloWorld -from modules.install.ToolsInstaller import ToolsInstaller +import modules.bashrc as bashrc +import modules.fail2ban as fail2ban +import modules.hacker as hacker +import modules.helloworld as helloworld +import modules.install as install +import modules.systemupdate as update +import modules.teamspeak as teamspeak from modules.swap.SwapModule import SwapModule -from modules.systemupdate.Systemupdate import Systemupdate from modules.vim.VimModule import VimModule -from modules.teamspeak.Teamspeak import Teamspeak -from modules.hacker.Hacker import Hacker -import modules.fail2ban.Fail2BanModule as fail2ban -from modules.bashrc.BashrcModule import BashrcModule modules = { - "helloworld": HelloWorld().run, - "install": ToolsInstaller, + "bashrc": bashrc.functions, + "fail2ban": fail2ban.functions, + "hacker": hacker.functions, + "helloworld": helloworld.functions, + "install": install.functions, "swap": SwapModule().run, - "update": Systemupdate().run, + "update": update.functions, + "teamspeak": teamspeak.functions, "vim": VimModule().run, - "teamspeak": Teamspeak, - "hacker": Hacker, - "fail2ban": fail2ban.run, - "bashrc": BashrcModule().run } fire.Fire(modules) diff --git a/modules/bashrc/BashrcModule.py b/modules/bashrc/BashrcModule.py deleted file mode 100644 index 7f77174..0000000 --- a/modules/bashrc/BashrcModule.py +++ /dev/null @@ -1,26 +0,0 @@ -from PyInquirer import prompt -import os -from shutil import copyfile -from print_helpers import print_gr, print_fail - - -class BashrcModule: - - def run(self): - bashrc_path = os.path.join(os.path.expanduser('~'), ".bashrc") - bashrc_exists = os.path.exists(bashrc_path) - - if bashrc_exists: - print_gr(f"Found .bashrc in {bashrc_path}") - ask_to_keep = { - 'type': 'confirm', - 'message': 'Do you want to overwrite the existing .bashrc?', - 'name': 'overwrite', - 'default': False, - } - if not prompt(ask_to_keep)['overwrite']: - print_fail("Stopping") - return - - copyfile("./modules/bashrc/bashrc_default", bashrc_path) - print_gr("Successfully overwritten .bashrc!") if bashrc_exists else print_gr(f"Successfully created .bashrc!") diff --git a/modules/bashrc/__init__.py b/modules/bashrc/__init__.py new file mode 100644 index 0000000..98297b2 --- /dev/null +++ b/modules/bashrc/__init__.py @@ -0,0 +1,31 @@ +import os +from shutil import copyfile + +from PyInquirer import prompt + +from print_helpers import print_gr, print_fail + + +def run(): + bashrc_path = os.path.join(os.path.expanduser('~'), ".bashrc") + bashrc_exists = os.path.exists(bashrc_path) + + if bashrc_exists: + print_gr(f"Found .bashrc in {bashrc_path}") + ask_to_keep = { + 'type': 'confirm', + 'message': 'Do you want to overwrite the existing .bashrc?', + 'name': 'overwrite', + 'default': False, + } + if not prompt(ask_to_keep)['overwrite']: + print_fail("Stopping") + return + + copyfile("./modules/bashrc/bashrc_default", bashrc_path) + print_gr("Successfully overwritten .bashrc!") if bashrc_exists else print_gr(f"Successfully created .bashrc!") + + +functions = { + "run": run, +} diff --git a/modules/fail2ban/Fail2BanModule.py b/modules/fail2ban/__init__.py similarity index 94% rename from modules/fail2ban/Fail2BanModule.py rename to modules/fail2ban/__init__.py index 6520387..8f1ff35 100644 --- a/modules/fail2ban/Fail2BanModule.py +++ b/modules/fail2ban/__init__.py @@ -13,3 +13,8 @@ def run(): subprocess.call("ufw allow ssh && ufw enable", shell=True) copyfile("./modules/fail2ban/jail.local", "/etc/fail2ban/jail.local") + + +functions = { + "run": run +} diff --git a/modules/hacker/Hacker.py b/modules/hacker/Hacker.py deleted file mode 100644 index 17b83a5..0000000 --- a/modules/hacker/Hacker.py +++ /dev/null @@ -1,29 +0,0 @@ -import subprocess -from os import path -import os -import random - - -class Hacker: - - def run_bash(self): - try: - subprocess.run("bash hacker.sh", shell=True, cwd=path.dirname(__file__)) - except KeyboardInterrupt: - pass - - def run_py(self): - columns = int(os.popen('stty size', 'r').read().split()[1]) # length of current line - try: - while True: - num_to_show = random.randint(0, 1) - count = random.randint(3, columns // 20) - hacker = " " * columns - for i in range(count): - pos = random.randint(0, columns) - hacker = hacker[:pos] + str(num_to_show) + hacker[pos+1:] - print("\033[92m" + hacker) - except KeyboardInterrupt: - print(columns) - print("Finished") - print("\033[0m") diff --git a/modules/hacker/__init__.py b/modules/hacker/__init__.py new file mode 100644 index 0000000..cdcf758 --- /dev/null +++ b/modules/hacker/__init__.py @@ -0,0 +1,34 @@ +import os +import random +import subprocess +from os import path + + +def run_bash(): + try: + subprocess.run("bash hacker.sh", shell=True, cwd=path.dirname(__file__)) + except KeyboardInterrupt: + pass + + +def run_py(): + columns = int(os.popen('stty size', 'r').read().split()[1]) # length of current line + try: + while True: + num_to_show = random.randint(0, 1) + count = random.randint(3, columns // 20) + hacker = " " * columns + for i in range(count): + pos = random.randint(0, columns) + hacker = hacker[:pos] + str(num_to_show) + hacker[pos + 1:] + print("\033[92m" + hacker) + except KeyboardInterrupt: + print(columns) + print("Finished") + print("\033[0m") + + +functions = { + "runBash": run_bash, + "runPy": run_py +} diff --git a/modules/helloworld/HelloWorld.py b/modules/helloworld/HelloWorld.py deleted file mode 100644 index 50975bb..0000000 --- a/modules/helloworld/HelloWorld.py +++ /dev/null @@ -1,13 +0,0 @@ -import subprocess - - -class HelloWorld: - """docstring for SampleModule.""" - - def run(self): - print("This shows that your installation is working correctly.") - subprocess.call("screenfetch", shell=True) - print("You can now start using the tool.") - output = subprocess.check_output("cat /etc/*-release", shell=True).decode("UTF-8") - with open("your_system_information.txt", "w") as file: - file.write(output) diff --git a/modules/helloworld/__init__.py b/modules/helloworld/__init__.py index e69de29..899a56f 100644 --- a/modules/helloworld/__init__.py +++ b/modules/helloworld/__init__.py @@ -0,0 +1,16 @@ +"""Docstring""" +import subprocess + +from print_helpers import print_gr + + +def helloworld(): + print_gr("This shows that your installation is working correctly.") + subprocess.call("screenfetch", shell=True) + print_gr("You can now start using the tool.") + output = subprocess.check_output("cat /etc/*-release", shell=True).decode("UTF-8") + with open("your_system_information.txt", "w") as file: + file.write(output) + + +functions = helloworld diff --git a/modules/install/ToolsInstaller.py b/modules/install/ToolsInstaller.py deleted file mode 100644 index e6c64f9..0000000 --- a/modules/install/ToolsInstaller.py +++ /dev/null @@ -1,22 +0,0 @@ -import subprocess - - -class ToolsInstaller: - - def basic_tools(self): - """Install the most basic tools!""" - print("Try to install basic Command-line tools") - subprocess.run("apt-get install -y bleachbit nano xrdp htop bash-completion dialog powertop tree wget", - shell=True) - print("Script ran to completion.") - - def hard_drive_tools(self): - """Install tools to look up smart information from your hard-drives""" - subprocess.run("apt-get install -y smartmontools gsmartcontrol", shell=True) - - def docker(self): - """Install the Docker service on the machine""" - subprocess.run("curl -fsSL https://get.docker.com | bash", shell=True) - subprocess.run("curl -L \"https://github.com/docker/compose/releases/download/" - "1.25.4/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose" - "&& chmod +x /usr/local/bin/docker-compose", shell=True) diff --git a/modules/install/__init__.py b/modules/install/__init__.py index e69de29..344a72b 100644 --- a/modules/install/__init__.py +++ b/modules/install/__init__.py @@ -0,0 +1,29 @@ +import subprocess + + +def basic_tools(): + """Install the most basic tools!""" + print("Try to install basic Command-line tools") + subprocess.run("apt-get install -y bleachbit nano xrdp htop bash-completion dialog powertop tree wget", + shell=True) + print("Script ran to completion.") + + +def hard_drive_tools(): + """Install tools to look up smart information from your hard-drives""" + subprocess.run("apt-get install -y smartmontools gsmartcontrol", shell=True) + + +def docker(): + """Install the Docker service on the machine""" + subprocess.run("curl -fsSL https://get.docker.com | bash", shell=True) + subprocess.run("curl -L \"https://github.com/docker/compose/releases/download/" + "1.25.4/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose" + "&& chmod +x /usr/local/bin/docker-compose", shell=True) + + +functions = { + "basictools": basic_tools, + "harddrive": hard_drive_tools, + "docker": docker +} diff --git a/modules/systemupdate/Systemupdate.py b/modules/systemupdate/Systemupdate.py deleted file mode 100644 index fe8a81d..0000000 --- a/modules/systemupdate/Systemupdate.py +++ /dev/null @@ -1,13 +0,0 @@ -import subprocess - - -class Systemupdate: - - def run(self): - print("Running update") - subprocess.call(["apt", "update", "-y"]) - subprocess.call(["apt", "upgrade", "-y"]) - subprocess.call(["apt", "dist-upgrade", "-y"]) - subprocess.call(["apt", "autoremove", "-y"]) - subprocess.call(["apt", "autoclean", "-y"]) - print("All update processes finished, please check output for further details.") diff --git a/modules/systemupdate/__init__.py b/modules/systemupdate/__init__.py index e69de29..896bada 100644 --- a/modules/systemupdate/__init__.py +++ b/modules/systemupdate/__init__.py @@ -0,0 +1,16 @@ +import subprocess + + +def run(): + print("Running update") + subprocess.call(["apt", "update", "-y"]) + subprocess.call(["apt", "upgrade", "-y"]) + subprocess.call(["apt", "dist-upgrade", "-y"]) + subprocess.call(["apt", "autoremove", "-y"]) + subprocess.call(["apt", "autoclean", "-y"]) + print("All update processes finished, please check output for further details.") + + +functions = { + "run": run +} diff --git a/modules/teamspeak/Teamspeak.py b/modules/teamspeak/Teamspeak.py deleted file mode 100644 index 294bb2c..0000000 --- a/modules/teamspeak/Teamspeak.py +++ /dev/null @@ -1,32 +0,0 @@ -import subprocess -from os import path -import time -import re - - -class Teamspeak: - """Manage a Docker backed Teamspeak server""" - - def start(self): - """Starts a Teamspeak Server with docker-compose""" - show_creds = False if path.exists(path.join(path.dirname(__file__), "ts3_data")) else True - subprocess.run("docker-compose up -d", shell=True, cwd=path.dirname(__file__)) - if show_creds: - logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode("UTF-8") - while re.search(r"token", logs) is None: - time.sleep(2) - logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode("UTF-8") - print("Server Query Admin Account: " + re.search(r"loginname=.*", logs).group(0)) - print("Server Admin Token: " + re.search(r"token=(.*)", logs).group(1)) - - def stop(self): - """Stops the Teamspeak Server with docker-compose""" - subprocess.run("docker-compose down -v", shell=True, cwd=path.dirname(__file__)) - - def pack_data(self, name="ts3_data.tar.gz"): - """Pack all user data of the server started with this script as tar file""" - subprocess.run(f"tar -zcvf {name} ts3_data", shell=True, cwd=path.dirname(__file__)) - - def show_logs(self): - """show the logs of the running Teamspeak server""" - subprocess.run("docker-compose logs", shell=True, cwd=path.dirname(__file__)) diff --git a/modules/teamspeak/__init__.py b/modules/teamspeak/__init__.py new file mode 100644 index 0000000..91296f9 --- /dev/null +++ b/modules/teamspeak/__init__.py @@ -0,0 +1,40 @@ +import re +import subprocess +import time +from os import path + + +def start(): + """Starts a Teamspeak Server with docker-compose""" + show_creds = False if path.exists(path.join(path.dirname(__file__), "ts3_data")) else True + subprocess.run("docker-compose up -d", shell=True, cwd=path.dirname(__file__)) + if show_creds: + logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode("UTF-8") + while re.search(r"token", logs) is None: + time.sleep(2) + logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode("UTF-8") + print("Server Query Admin Account: " + re.search(r"loginname=.*", logs).group(0)) + print("Server Admin Token: " + re.search(r"token=(.*)", logs).group(1)) + + +def stop(): + """Stops the Teamspeak Server with docker-compose""" + subprocess.run("docker-compose down -v", shell=True, cwd=path.dirname(__file__)) + + +def pack_data(name="ts3_data.tar.gz"): + """Pack all user data of the server started with this script as tar file""" + subprocess.run(f"tar -zcvf {name} ts3_data", shell=True, cwd=path.dirname(__file__)) + + +def show_logs(): + """show the logs of the running Teamspeak server""" + subprocess.run("docker-compose logs", shell=True, cwd=path.dirname(__file__)) + + +functions = { + "start": start, + "stop": stop, + "pack": pack_data, + "logs": show_logs +} From d3fc426f999e34fc8a1f6b03c4178abb20da90a9 Mon Sep 17 00:00:00 2001 From: Marcel Schwarz Date: Sun, 2 Aug 2020 00:56:08 +0200 Subject: [PATCH 02/10] Update python fire and add README.md --- README.md | 9 +++++++++ requirements.txt | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..29cf8c4 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# About + +# How to start a dev env + +```shell script +docker run --rm -it -v $(pwd):/data/linux-tools ubuntu bash +``` + +# Contributing \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index c72786b..df7c954 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -fire +fire==0.3.1 PyInquirer==1.0.3 From 36edc4c1833d361767bd4bdaa07cb90bd513c653 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 03:50:50 +0200 Subject: [PATCH 03/10] Remove class structure from vim module --- main.py | 4 +- modules/vim/VimModule.py | 104 --------------------------------------- modules/vim/__init__.py | 92 ++++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 106 deletions(-) delete mode 100644 modules/vim/VimModule.py diff --git a/main.py b/main.py index 41c80e8..00c1d86 100644 --- a/main.py +++ b/main.py @@ -7,8 +7,8 @@ import modules.helloworld as helloworld import modules.install as install import modules.systemupdate as update import modules.teamspeak as teamspeak +import modules.vim as vim from modules.swap.SwapModule import SwapModule -from modules.vim.VimModule import VimModule modules = { "bashrc": bashrc.functions, @@ -19,7 +19,7 @@ modules = { "swap": SwapModule().run, "update": update.functions, "teamspeak": teamspeak.functions, - "vim": VimModule().run, + "vim": vim.functions, } fire.Fire(modules) diff --git a/modules/vim/VimModule.py b/modules/vim/VimModule.py deleted file mode 100644 index 8cf26ce..0000000 --- a/modules/vim/VimModule.py +++ /dev/null @@ -1,104 +0,0 @@ -import json -import os -import subprocess -from pathlib import Path - -from PyInquirer import prompt - - -class VimModule: - def __init__(self): - super().__init__() - self._debugFlag = False - self._json_config = {} - with open("modules/vim/vimrc_conf.json") as plugins: - self._json_config = json.load(plugins) - - def _get_vim_root(self): - if self._debugFlag: - return Path(os.getcwd()).joinpath("devenv", ".vim") - else: - return Path().home().joinpath(".vim") - - def _create_folder_structure(self): - os.makedirs(str(self._get_vim_root().joinpath("autoload")), exist_ok=True) - os.makedirs(str(self._get_vim_root().joinpath("plugged")), exist_ok=True) - - def _get_vimplug_file(self): - vimplug_filepath = Path(str(self._get_vim_root().joinpath("autoload"))) - print(vimplug_filepath) - if os.path.isfile(str(self._get_vim_root().joinpath("autoload", "plug.vim"))): - print("Vimplug already installed!") - else: - curl_request = "curl {} -o {}".format( - self._json_config['pluginmanager_url'], - str(self._get_vim_root().joinpath("autoload", "plug.vim")) - ) - subprocess.call(curl_request, shell=True) - - def _create_plugin_section(self): - vimrc_content = [] - plugins = self._json_config['plugins'] - print("Available Plugins:") - plugin_selection = [ - { - 'type': 'checkbox', - 'message': 'Select plugins', - 'name': 'modules', - 'choices': list(map(lambda x: {"name": x}, plugins.keys())) - } - ] - selected_plugins = prompt(plugin_selection)['modules'] - if len(selected_plugins) > 0: - self._get_vimplug_file() - print("\033[4mYour selection:\033[0m") - [print(x) for x in selected_plugins] - - vimrc_content.append("call plug#begin('~/.vim/plugged')\n") - for element in selected_plugins: - vimrc_content.append(plugins[element] + "\n") - vimrc_content.append("call plug#end()\n") - - return vimrc_content - - def _create_setting_section(self): - default_settings = list(self._json_config['settings'].values()) - - print("\n\033[4mDefault settings:\033[0m") - [print(i) for i in default_settings] - - vimrc_content = list(map(lambda x: x + "\n", default_settings)) - return vimrc_content - - def _get_vimfile_working_copy(self): - vimrc_path = str(self._get_vim_root().joinpath(".vimrc")) - try: - with open(vimrc_path, "r") as vimrc_file: - vimrc_content = vimrc_file.readlines() - except FileNotFoundError: - vimrc_content = [] - - return vimrc_content - - def _write_vimfile(self, vimrc_content): - seen = set() - seen_add = seen.add - vimrc_content = [x1 for x1 in vimrc_content if not (x1 in seen or seen_add(x1))] - - vimrc_path = str(self._get_vim_root().joinpath(".vimrc")) - with open(vimrc_path, "w") as vimrc_file: - for line in vimrc_content: - vimrc_file.write(line) - - def _exec_plugin_manager(self): - install_plugins = "vim +PlugInstall +qall +silent" - subprocess.call(install_plugins, shell=True) - - def run(self, debug=False): - if debug: - self._debugFlag = True - self._create_folder_structure() - plugin_section = self._create_plugin_section() - settings_section = self._create_setting_section() - self._write_vimfile(settings_section + plugin_section) - self._exec_plugin_manager() diff --git a/modules/vim/__init__.py b/modules/vim/__init__.py index e69de29..48b4b1b 100644 --- a/modules/vim/__init__.py +++ b/modules/vim/__init__.py @@ -0,0 +1,92 @@ +import json +import os +import subprocess +from pathlib import Path + +from PyInquirer import prompt + +vim_root = Path().home().joinpath(".vim") +vimrc_path = str(Path().home().joinpath(".vimrc")) +json_config = {} + + +def create_plugin_section(): + plugins = json_config['plugins'] + print("Available Plugins:") + plugin_selection = [ + { + 'type': 'checkbox', + 'message': 'Select plugins', + 'name': 'modules', + 'choices': list(map(lambda x: {"name": x}, plugins.keys())) + } + ] + selected_plugins = prompt(plugin_selection)['modules'] + print("\033[4mYour selection:\033[0m") + [print(x) for x in selected_plugins] + + # Install vimplug if plugins selected + vimplug_path = str(vim_root.joinpath("autoload", "plug.vim")) + if selected_plugins and not os.path.isfile(vimplug_path): + curl_request = f"curl {json_config['pluginmanager_url']} -o {vimplug_path}" + subprocess.call(curl_request, shell=True) + print("Pluginmanager was set up") + + vimrc_content = ["call plug#begin('~/.vim/plugged')\n"] + for element in selected_plugins: + vimrc_content.append(plugins[element] + "\n") + vimrc_content.append("call plug#end()\n") + return vimrc_content + + +def create_setting_section(): + default_settings = list(json_config['settings'].values()) + + print("\n\033[4mDefault settings:\033[0m") + [print(i) for i in default_settings] + + vimrc_content = list(map(lambda x: x + "\n", default_settings)) + return vimrc_content + + +def write_vimfile(vimrc_content): + seen = set() + seen_add = seen.add + vimrc_content = [x1 for x1 in vimrc_content if not (x1 in seen or seen_add(x1))] + + with open(vimrc_path, "w") as vimrc_file: + for line in vimrc_content: + vimrc_file.write(line) + + +# Unused +def _get_vimfile_working_copy(): + try: + with open(vimrc_path, "r") as vimrc_file: + vimrc_content = vimrc_file.readlines() + except FileNotFoundError: + vimrc_content = [] + return vimrc_content + + +def run(): + global json_config + with open("modules/vim/vimrc_conf.json", "r") as config: + json_config = json.load(config) + + # Create folders + os.makedirs(str(vim_root.joinpath("autoload")), exist_ok=True) + os.makedirs(str(vim_root.joinpath("plugged")), exist_ok=True) + + plugin_section = create_plugin_section() + settings_section = create_setting_section() + + write_vimfile(settings_section + plugin_section) + + # Exec plugin manager + install_plugins = "vim +PlugInstall +qall" + subprocess.call(install_plugins, shell=True) + print("Module finished successfully!") + + +functions = run From 94ff8d2ce2a360b8a83762c85f398839f56bfa79 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 03:51:01 +0200 Subject: [PATCH 04/10] Add new plugins for vim module --- modules/vim/vimrc_conf.json | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/vim/vimrc_conf.json b/modules/vim/vimrc_conf.json index 8271c78..0fe27a3 100644 --- a/modules/vim/vimrc_conf.json +++ b/modules/vim/vimrc_conf.json @@ -1,12 +1,16 @@ { "pluginmanager_url": "https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim", "plugins": { - "Colorschemes": "Plug 'https://github.com/rafi/awesome-vim-colorschemes.git'", - "Unix Operations": "Plug 'https://github.com/tpope/vim-eunuch.git'", + "AutoPair": "Plug 'https://github.com/jiangmiao/auto-pairs.git'", "Emmet": "Plug 'https://github.com/mattn/emmet-vim.git'", + "Jellybeans Theme": "Plug 'https://github.com/nanotech/jellybeans.vim.git'", "Meta5 Theme": "Plug 'https://github.com/christophermca/meta5.git'", "Nerdtree": "Plug 'https://github.com/scrooloose/nerdtree'", - "Lightline": "Plug 'https://github.com/itchyny/lightline.vim'" + "Vim Airline": "Plug 'https://github.com/vim-airline/vim-airline.git'", + "Onedark Theme": "Plug 'https://github.com/joshdick/onedark.vim.git'", + "Malokai Theme": "Plug 'kiddos/malokai.vim'", + "Monokai Theme": "Plug 'crusoexia/vim-monokai'", + "JavaScript Extension": "Plug 'pangloss/vim-javascript'" }, "settings": { "tabstop": "set tabstop=2", From ecc63013c15f2459f7804e11e8408a8b13ecdd28 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 03:51:22 +0200 Subject: [PATCH 05/10] Remove xrdp from basictools add git and vim --- modules/install/__init__.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/install/__init__.py b/modules/install/__init__.py index 344a72b..ce0c49e 100644 --- a/modules/install/__init__.py +++ b/modules/install/__init__.py @@ -4,8 +4,10 @@ import subprocess def basic_tools(): """Install the most basic tools!""" print("Try to install basic Command-line tools") - subprocess.run("apt-get install -y bleachbit nano xrdp htop bash-completion dialog powertop tree wget", - shell=True) + subprocess.run( + "apt update && apt-get install -y bleachbit nano htop bash-completion dialog powertop tree wget vim git", + shell=True + ) print("Script ran to completion.") From b09431877e2506846f73534a0760a62acd3f22d8 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 04:16:30 +0200 Subject: [PATCH 06/10] Check if lnxtools.sh is run as root Update requirements.txt Update wording --- lnxtools.sh | 6 +++++- modules/helloworld/__init__.py | 5 +++-- modules/install/__init__.py | 4 +++- requirements.txt | 3 +++ 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lnxtools.sh b/lnxtools.sh index e4ee61b..17feb51 100755 --- a/lnxtools.sh +++ b/lnxtools.sh @@ -1,5 +1,10 @@ #!/bin/bash +if [[ $EUID -ne 0 ]]; then + echo "This script must be run as root" + exit 1 +fi + DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" cd "$DIR" || exit FILE=./your_system_information.txt @@ -8,7 +13,6 @@ if [ ! -f "$FILE" ]; then echo "Preparing your system for the first run" apt-get update -y && apt-get upgrade -y apt-get install curl screenfetch python3.7 python3-pip -y - pip3 install setuptools wheel regex pip3 install -r requirements.txt python3 main.py helloworld else diff --git a/modules/helloworld/__init__.py b/modules/helloworld/__init__.py index 899a56f..bae0abf 100644 --- a/modules/helloworld/__init__.py +++ b/modules/helloworld/__init__.py @@ -5,9 +5,10 @@ from print_helpers import print_gr def helloworld(): - print_gr("This shows that your installation is working correctly.") + print_gr("This shows that your installation is working correctly") subprocess.call("screenfetch", shell=True) - print_gr("You can now start using the tool.") + print_gr("You can now proceed with setting up individual modules") + print_gr("Run ./lnxtools.sh to see all available commands") output = subprocess.check_output("cat /etc/*-release", shell=True).decode("UTF-8") with open("your_system_information.txt", "w") as file: file.write(output) diff --git a/modules/install/__init__.py b/modules/install/__init__.py index ce0c49e..ae74316 100644 --- a/modules/install/__init__.py +++ b/modules/install/__init__.py @@ -1,5 +1,7 @@ import subprocess +from print_helpers import print_gr + def basic_tools(): """Install the most basic tools!""" @@ -8,7 +10,7 @@ def basic_tools(): "apt update && apt-get install -y bleachbit nano htop bash-completion dialog powertop tree wget vim git", shell=True ) - print("Script ran to completion.") + print_gr("Module basictools has successfully finished!") def hard_drive_tools(): diff --git a/requirements.txt b/requirements.txt index df7c954..9bf425a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,5 @@ fire==0.3.1 PyInquirer==1.0.3 +regex==2020.7.14 +wheel==0.34.2 +setuptools==49.2.0 From c067b8c89d06f225c42da03cc33e3dac6414b107 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 13:58:47 +0200 Subject: [PATCH 07/10] Use print helper functions --- modules/fail2ban/__init__.py | 4 +++- modules/hacker/__init__.py | 7 ++++--- modules/install/__init__.py | 4 ++-- modules/systemupdate/__init__.py | 4 +++- modules/teamspeak/__init__.py | 9 ++++++--- modules/vim/__init__.py | 10 ++++++---- print_helpers.py | 4 ++++ 7 files changed, 28 insertions(+), 14 deletions(-) diff --git a/modules/fail2ban/__init__.py b/modules/fail2ban/__init__.py index 8f1ff35..0dd2623 100644 --- a/modules/fail2ban/__init__.py +++ b/modules/fail2ban/__init__.py @@ -1,13 +1,15 @@ import subprocess from shutil import copyfile +from print_helpers import print_bold + def run(): subprocess.call("apt install fail2ban -y", shell=True) try: ufw_is_installed = subprocess.check_output("which ufw", shell=True).decode().strip() - print(f"ufw is already installed in {ufw_is_installed}") + print_bold(f"ufw is already installed in {ufw_is_installed}") except subprocess.CalledProcessError: subprocess.call("sudo apt install ufw -y", shell=True) subprocess.call("ufw allow ssh && ufw enable", shell=True) diff --git a/modules/hacker/__init__.py b/modules/hacker/__init__.py index cdcf758..5bd05ab 100644 --- a/modules/hacker/__init__.py +++ b/modules/hacker/__init__.py @@ -3,6 +3,8 @@ import random import subprocess from os import path +from print_helpers import print_gr + def run_bash(): try: @@ -21,11 +23,10 @@ def run_py(): for i in range(count): pos = random.randint(0, columns) hacker = hacker[:pos] + str(num_to_show) + hacker[pos + 1:] - print("\033[92m" + hacker) + print_gr(hacker) except KeyboardInterrupt: print(columns) - print("Finished") - print("\033[0m") + print_gr("Finished") functions = { diff --git a/modules/install/__init__.py b/modules/install/__init__.py index ae74316..aac56b1 100644 --- a/modules/install/__init__.py +++ b/modules/install/__init__.py @@ -1,11 +1,11 @@ import subprocess -from print_helpers import print_gr +from print_helpers import print_warn, print_gr def basic_tools(): """Install the most basic tools!""" - print("Try to install basic Command-line tools") + print_warn("Try to install basic Command-line tools") subprocess.run( "apt update && apt-get install -y bleachbit nano htop bash-completion dialog powertop tree wget vim git", shell=True diff --git a/modules/systemupdate/__init__.py b/modules/systemupdate/__init__.py index 896bada..eebd2fc 100644 --- a/modules/systemupdate/__init__.py +++ b/modules/systemupdate/__init__.py @@ -1,5 +1,7 @@ import subprocess +from print_helpers import print_gr + def run(): print("Running update") @@ -8,7 +10,7 @@ def run(): subprocess.call(["apt", "dist-upgrade", "-y"]) subprocess.call(["apt", "autoremove", "-y"]) subprocess.call(["apt", "autoclean", "-y"]) - print("All update processes finished, please check output for further details.") + print_gr("All update processes finished, please check output for further details.") functions = { diff --git a/modules/teamspeak/__init__.py b/modules/teamspeak/__init__.py index 91296f9..620af06 100644 --- a/modules/teamspeak/__init__.py +++ b/modules/teamspeak/__init__.py @@ -3,6 +3,8 @@ import subprocess import time from os import path +from print_helpers import print_bold + def start(): """Starts a Teamspeak Server with docker-compose""" @@ -12,9 +14,10 @@ def start(): logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode("UTF-8") while re.search(r"token", logs) is None: time.sleep(2) - logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode("UTF-8") - print("Server Query Admin Account: " + re.search(r"loginname=.*", logs).group(0)) - print("Server Admin Token: " + re.search(r"token=(.*)", logs).group(1)) + logs = subprocess.check_output("docker-compose logs", shell=True, cwd=path.dirname(__file__)).decode( + "UTF-8") + print_bold("Server Query Admin Account: " + re.search(r"loginname=.*", logs).group(0)) + print_bold("Server Admin Token: " + re.search(r"token=(.*)", logs).group(1)) def stop(): diff --git a/modules/vim/__init__.py b/modules/vim/__init__.py index 48b4b1b..71dd288 100644 --- a/modules/vim/__init__.py +++ b/modules/vim/__init__.py @@ -5,6 +5,8 @@ from pathlib import Path from PyInquirer import prompt +from print_helpers import print_gr, print_bold + vim_root = Path().home().joinpath(".vim") vimrc_path = str(Path().home().joinpath(".vimrc")) json_config = {} @@ -22,7 +24,7 @@ def create_plugin_section(): } ] selected_plugins = prompt(plugin_selection)['modules'] - print("\033[4mYour selection:\033[0m") + print_bold("Your selection:") [print(x) for x in selected_plugins] # Install vimplug if plugins selected @@ -30,7 +32,7 @@ def create_plugin_section(): if selected_plugins and not os.path.isfile(vimplug_path): curl_request = f"curl {json_config['pluginmanager_url']} -o {vimplug_path}" subprocess.call(curl_request, shell=True) - print("Pluginmanager was set up") + print_gr("Pluginmanager was set up") vimrc_content = ["call plug#begin('~/.vim/plugged')\n"] for element in selected_plugins: @@ -42,7 +44,7 @@ def create_plugin_section(): def create_setting_section(): default_settings = list(json_config['settings'].values()) - print("\n\033[4mDefault settings:\033[0m") + print_bold("Default settings:") [print(i) for i in default_settings] vimrc_content = list(map(lambda x: x + "\n", default_settings)) @@ -86,7 +88,7 @@ def run(): # Exec plugin manager install_plugins = "vim +PlugInstall +qall" subprocess.call(install_plugins, shell=True) - print("Module finished successfully!") + print_gr("Module finished successfully!") functions = run diff --git a/print_helpers.py b/print_helpers.py index de0c70c..77a552f 100644 --- a/print_helpers.py +++ b/print_helpers.py @@ -12,3 +12,7 @@ def print_warn(text): def print_blue(text): print("\033[94m" + "[+] " + text + "\033[0m") + + +def print_bold(text): + print("\033[1m" + text + "\033[0m") From 1a242827a9938a818b7cb0e13355e6a15644bf3c Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 23:22:50 +0200 Subject: [PATCH 08/10] Remove old SwapModule.py --- modules/swap/SwapModule.py | 154 ------------------------------------- 1 file changed, 154 deletions(-) delete mode 100644 modules/swap/SwapModule.py diff --git a/modules/swap/SwapModule.py b/modules/swap/SwapModule.py deleted file mode 100644 index 88d8c50..0000000 --- a/modules/swap/SwapModule.py +++ /dev/null @@ -1,154 +0,0 @@ -import subprocess -from typing import List - -from PyInquirer import prompt - - -def _run_shell_command(cmd: List[str]) -> str: - return subprocess.check_output(cmd).decode("UTF-8").strip() - - -class SwapModule: - - def run(self): - actions = { - "Create/Resize temp. swap": self._create_resize_swap, - "Create/Resize persistent swap": self._create_resize_persistent_swap, - "Delete swap": self._delete_swap, - "Make temp. swap persistent": self._make_swap_persistent, - "Get swap location": self._get_swap_location, - "Get swap size": self._get_swap_size, - "Show swapiness": self._show_swapiness, - "Adjust temp. swapiness": self._adjust_swapiness_temp, - "Check fstab for entry": self._fstab_entry_exists - } - menu = [ - { - 'type': 'list', - 'message': 'Select action', - 'name': 'action', - 'choices': list(map(lambda x: {"name": x}, actions.keys())) - } - ] - selected_action = prompt(menu)['action'] - actions[selected_action]() - - def _create_resize_persistent_swap(self): - self._create_resize_swap() - self._make_swap_persistent() - - def _get_swap_location(self): - output_swaps = _run_shell_command(["cat", "/proc/swaps"]) - try: - swap_location = output_swaps.split()[5] - print("Swap is located here:", swap_location) - return swap_location - except IndexError: - print("Swap file doesn´t exist!") - return None - - def _get_swap_size(self): - swap_size = _run_shell_command(['swapon', '--show']) - try: - swap_size = swap_size.split()[7] - print("Swap is {}b big!".format(swap_size)) - except IndexError: - print("Swap file doesn´t exist!") - - def _create_resize_swap(self): - output_swapon = _run_shell_command(['swapon', '--show']) - if output_swapon is not "": - swap_size = output_swapon.split()[7] - print("") - print("Swap already installed! You can resize it!") - print("Curr. swap size: {}b".format(swap_size)) - resize = input("How big should your swap become (numbers in Gigabyte)? ") - resize_swapfile = "sudo swapoff /swapfile && " + \ - "sudo fallocate -l {}G /swapfile && ".format(resize) + \ - "sudo mkswap /swapfile && " + \ - "sudo swapon /swapfile" - subprocess.call(resize_swapfile, shell=True) - output_free = _run_shell_command(["free", "-h"]) - print(output_free.strip()) - - else: - size = input("How big should the swap be (numbers in Gigabyte)? ") - create_swapfile = "sudo fallocate -l {}G /swapfile && ".format(size) + \ - "sudo chmod 600 /swapfile && " + \ - "sudo mkswap /swapfile && " + \ - "sudo swapon /swapfile" - subprocess.call(create_swapfile, shell=True) - - output_free = _run_shell_command(["free", "-h"]) - print(output_free.strip()) - - def _make_swap_persistent(self): - swap_location = self._get_swap_location() - if swap_location is None: - print("Swap file doesn't exist!") - return - backup_fstab = "sudo cp /etc/fstab /etc/fstab.bak" - enable_persistence = "echo '{} none swap sw 0 0' | sudo tee -a /etc/fstab".format(swap_location) - if self._fstab_entry_exists(): - print("Swap is already persistent!") - else: - subprocess.call(backup_fstab, shell=True) - subprocess.call(enable_persistence, shell=True) - print("Swap is now persistent!") - - def _show_swapiness(self): - print(_run_shell_command(["cat", "/proc/sys/vm/swappiness"])) - - def _adjust_swapiness_temp(self): - options = { - "Light": 25, - "Default": 60, - "Aggressive": 100 - } - menu = [ - { - 'type': 'list', - 'message': 'Select action', - 'name': 'action', - 'choices': list(map(lambda x: {"name": x}, options.keys())) - } - ] - selected_swapiness = prompt(menu)['action'] - - adjust = "sudo sysctl vm.swappiness=" + str(options[selected_swapiness]) - subprocess.call(adjust, shell=True) - print("Temporary swapiness is " + str(options[selected_swapiness])) - - def _delete_swap(self): - swap_location = self._get_swap_location() - if swap_location is None: - return - disable_swapfile = "sudo swapoff {} && ".format(swap_location) + \ - "sudo rm {}".format(swap_location) - if self._fstab_entry_exists(): - with open("/etc/fstab", "r") as fstab_out: - content = fstab_out.readlines() - with open("/etc/fstab", "w") as fstab_in: - content = content[:-1] - for line in content: - fstab_in.write(line) - else: - print("No entry in /etc/fstab!") - subprocess.call(disable_swapfile, shell=True) - output_swapon = _run_shell_command(['swapon', '--show']) - output_free = _run_shell_command(["free", "-h"]) - if not output_swapon: - print("Swap deleted!") - print(output_free.strip()) - - def _fstab_entry_exists(self): - swap_location = self._get_swap_location() - fstab_entry = "{} none swap sw 0 0\n".format(swap_location) - with open("/etc/fstab", "r") as fstab_file: - line = fstab_file.readlines()[-1] - if line != fstab_entry: - print("No entry in /etc/fstab") - return False - else: - print("fstab entry:", line.strip()) - return True From d03fe99af0ac4f1706119a6ae6a3c177b9e51ad1 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 23:24:08 +0200 Subject: [PATCH 09/10] Remove class structure Add print helpers Remove unnecessary .strip() Remove unnecessary sudo commands --- main.py | 4 +- modules/swap/__init__.py | 166 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 168 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 00c1d86..04591c0 100644 --- a/main.py +++ b/main.py @@ -5,10 +5,10 @@ import modules.fail2ban as fail2ban import modules.hacker as hacker import modules.helloworld as helloworld import modules.install as install +import modules.swap as swap import modules.systemupdate as update import modules.teamspeak as teamspeak import modules.vim as vim -from modules.swap.SwapModule import SwapModule modules = { "bashrc": bashrc.functions, @@ -16,7 +16,7 @@ modules = { "hacker": hacker.functions, "helloworld": helloworld.functions, "install": install.functions, - "swap": SwapModule().run, + "swap": swap.run, "update": update.functions, "teamspeak": teamspeak.functions, "vim": vim.functions, diff --git a/modules/swap/__init__.py b/modules/swap/__init__.py index e69de29..e97418a 100644 --- a/modules/swap/__init__.py +++ b/modules/swap/__init__.py @@ -0,0 +1,166 @@ +import subprocess +from typing import List + +from PyInquirer import prompt + +from print_helpers import print_bold, print_warn, print_gr + + +def run_shell_command(cmd: List[str]) -> str: + return subprocess.check_output(cmd).decode("UTF-8").strip() + + +def create_resize_persistent_swap(): + create_resize_swap() + make_swap_persistent() + + +def get_swap_location(): + output_swaps = run_shell_command(["cat", "/proc/swaps"]) + try: + swap_location = output_swaps.split()[5] + print_bold(f"Swap is located here: {swap_location}") + return swap_location + except IndexError: + print_warn("Swap file doesn´t exist!") + return None + + +def get_swap_size(): + swap_size = run_shell_command(['swapon', '--show']) + try: + swap_size = swap_size.split()[7] + print_gr(f"Swap is {swap_size}b big!") + except IndexError: + print_warn("Swap file doesn´t exist!") + + +def create_resize_swap(): + output_swapon = run_shell_command(['swapon', '--show']) + if output_swapon is not "": + swap_size = output_swapon.split()[7] + print("") + print_bold("Swap already installed! You can resize it!") + print_bold(f"Curr. swap size: {swap_size}b") + resize = input("How big should your swap become (numbers in Gigabyte)? ") + resize_swapfile = "swapoff /swapfile && " + \ + f"fallocate -l {resize}G /swapfile && " + \ + "mkswap /swapfile && " + \ + "swapon /swapfile" + subprocess.call(resize_swapfile, shell=True) + output_free = run_shell_command(["free", "-h"]) + print_gr(output_free) + + else: + size = input("How big should the swap be (numbers in Gigabyte)? ") + create_swapfile = f"fallocate -l {size}G /swapfile && " + \ + "chmod 600 /swapfile && " + \ + "mkswap /swapfile && " + \ + "swapon /swapfile" + subprocess.call(create_swapfile, shell=True) + + output_free = run_shell_command(["free", "-h"]) + print_gr(output_free) + + +def make_swap_persistent(): + swap_location = get_swap_location() + if swap_location is None: + print_warn("Swap file doesn't exist!") + return + backup_fstab = "cp /etc/fstab /etc/fstab.bak" + enable_persistence = f"echo '{swap_location} none swap sw 0 0' | tee -a /etc/fstab" + if fstab_entry_exists(): + print_warn("Swap is already persistent!") + else: + subprocess.call(backup_fstab, shell=True) + subprocess.call(enable_persistence, shell=True) + print_gr("Swap is now persistent!") + + +def show_swapiness(): + print_gr(run_shell_command(["cat", "/proc/sys/vm/swappiness"])) + + +def adjust_swapiness_temp(): + options = { + "Light": 25, + "Default": 60, + "Aggressive": 100 + } + menu = [ + { + 'type': 'list', + 'message': 'Select action', + 'name': 'action', + 'choices': list(map(lambda x: {"name": x}, options.keys())) + } + ] + selected_swapiness = prompt(menu)['action'] + + adjust = "sysctl vm.swappiness=" + str(options[selected_swapiness]) + subprocess.call(adjust, shell=True) + print_gr("Temporary swapiness is " + str(options[selected_swapiness])) + + +def delete_swap(): + swap_location = get_swap_location() + if swap_location is None: + return + disable_swapfile = f"swapoff {swap_location} && " + \ + f"rm {swap_location}" + if fstab_entry_exists(): + with open("/etc/fstab", "r") as fstab_out: + content = fstab_out.readlines() + with open("/etc/fstab", "w") as fstab_in: + content = content[:-1] + for line in content: + fstab_in.write(line) + else: + print_warn("No entry in /etc/fstab!") + subprocess.call(disable_swapfile, shell=True) + output_swapon = run_shell_command(['swapon', '--show']) + output_free = run_shell_command(["free", "-h"]) + if not output_swapon: + print_gr("Swap deleted!") + print_gr(output_free) + + +def fstab_entry_exists(): + swap_location = get_swap_location() + fstab_entry = f"{swap_location} none swap sw 0 0\n" + with open("/etc/fstab", "r") as fstab_file: + line = fstab_file.readlines()[-1] + if line != fstab_entry: + print_warn("No entry in /etc/fstab") + return False + else: + print_gr(f"fstab entry: {line.strip()}") + return True + + +def run(): + actions = { + "Create/Resize temp. swap": create_resize_swap, + "Create/Resize persistent swap": create_resize_persistent_swap, + "Delete swap": delete_swap, + "Make temp. swap persistent": make_swap_persistent, + "Get swap location": get_swap_location, + "Get swap size": get_swap_size, + "Show swapiness": show_swapiness, + "Adjust temp. swapiness": adjust_swapiness_temp, + "Check fstab for entry": fstab_entry_exists, + } + menu = [ + { + 'type': 'list', + 'message': 'Select action', + 'name': 'action', + 'choices': list(map(lambda x: {"name": x}, actions.keys())) + } + ] + selected_action = prompt(menu)['action'] + actions[selected_action]() + + +functions = run From 51e208bd8c1a81aa1edb3ce3c6ac2b5a82e44530 Mon Sep 17 00:00:00 2001 From: Lucas Noki Date: Sun, 2 Aug 2020 23:52:14 +0200 Subject: [PATCH 10/10] Replace 'run' with 'functions' for best practice --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 04591c0..417bcc2 100644 --- a/main.py +++ b/main.py @@ -16,7 +16,7 @@ modules = { "hacker": hacker.functions, "helloworld": helloworld.functions, "install": install.functions, - "swap": swap.run, + "swap": swap.functions, "update": update.functions, "teamspeak": teamspeak.functions, "vim": vim.functions,