From 98fae3427e6791003e64572a2a6ca317c72473ef Mon Sep 17 00:00:00 2001 From: xiubuzhe Date: Sun, 15 Oct 2023 03:40:31 +0800 Subject: add bash-completion in /sbin/sunhpc-compxxxx-bak --- lib/sunhpc/commands/__init__.py | 12 +- lib/sunhpc/commands/build/init/__init__.py | 84 +++++++ lib/sunhpc/core/interpreter.py | 371 +++++++++++++++++++++++++++++ lib/sunhpc/core/utils.py | 8 +- 4 files changed, 468 insertions(+), 7 deletions(-) create mode 100644 lib/sunhpc/commands/build/init/__init__.py create mode 100644 lib/sunhpc/core/interpreter.py (limited to 'lib') diff --git a/lib/sunhpc/commands/__init__.py b/lib/sunhpc/commands/__init__.py index 75b7692..a8c6c5b 100644 --- a/lib/sunhpc/commands/__init__.py +++ b/lib/sunhpc/commands/__init__.py @@ -658,7 +658,7 @@ class Command(object): ender = '\033[95m%s\033[0m' % end msger = '\033[31m%s\033[0m' % msg result = '%s %s %s' % (header, msger, ender) - return result + print (result) def abort(self, msg): @@ -977,17 +977,17 @@ class Command(object): def getText(self): return self.text - def dictOutput(self, strDict, sep='\t'): + def dictOutput(self, strDict, sep=' '): maxlen = max(map(len, strDict.keys())) for k in strDict: strings = str(strDict[k]) if strings.strip().lower() in ['ok', 'on', 'yes']: - value = '|\033[1;32m %s \033[0m' % strings.upper() + value = '\033[1;32m %s \033[0m' % strings.upper() elif strings.strip().lower() in ['fail', 'off', 'no', 'error', 'failed']: - value = '|\033[1;31m %s \033[0m' % strings.upper() + value = '\033[1;31m %s \033[0m' % strings.upper() else: - value = '| %s' % strings - print ('\t\033[1;95m%s\033[0m %s \033[1;96m%s\033[0m' % (k.ljust(maxlen), sep, value)) + value = '%s' % strings + print ('\t\033[1;95m%s\033[0m %s = \033[1;96m%s\033[0m' % (k.ljust(maxlen), sep, value)) def beginFmtOutput(self, header=[]): self.fmtOutput = prettytable.PrettyTable(header) diff --git a/lib/sunhpc/commands/build/init/__init__.py b/lib/sunhpc/commands/build/init/__init__.py new file mode 100644 index 0000000..5a43ff2 --- /dev/null +++ b/lib/sunhpc/commands/build/init/__init__.py @@ -0,0 +1,84 @@ +# +#coding:utf-8 +# +#Author : QCSun +#Email : qcsun@sunhpc.com +#Times : 2023-04-14 05:21:02 +#WebSite : https://www.sunhpc.com + +import os +import re +import sys +import sunhpc +import readline +from sunhpc.core.interpreter import SunhpcInterpreter + +class Struct(object): + pass + +class command(sunhpc.commands.build.command): + pass + +class Command(command, SunhpcInterpreter): +#class Command(command): + """ + Initialzed the sunhpc database. + """ + def run(self, params, args): + SunhpcInterpreter.__init__(self) + + self.results = {} + self.results['country'] = 'CN' + self.results['state'] = 'LiaoNing' + self.results['city'] = 'Dalian' + self.results['url'] = 'https://www.sunhpc.com' + + self.current_keys = list(self.results.keys()) + self.current_values = self.results + + self.start() + + def preceding(self): + print(' 下列是数据库的初始化配置的基础选项.') + print(' 可以使用命令 set key=value 进行修改:\n') + self.dictOutput(self.results) + print(' ---------------------------------------------\n') + + def _SunhpcInterpreter__show_all(self, root=''): + + self.dictOutput(self.current_values) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/sunhpc/core/interpreter.py b/lib/sunhpc/core/interpreter.py new file mode 100644 index 0000000..2983096 --- /dev/null +++ b/lib/sunhpc/core/interpreter.py @@ -0,0 +1,371 @@ +# +#coding:utf-8 +# +#Author : QCSun +#Email : qcsun@sunhpc.com +#Times : 2023-04-14 05:21:02 +#WebSite : https://www.sunhpc.com + +import os +import re +import sys +import queue +import atexit +import textwrap +import readline +import itertools + +from sunhpc.core.utils import SunhpcCliException + +GLOBAL_OPTS = {} + +def is_libedit(): + return "libedit" in readline.__doc__ + +class BaseInterpreter(object): + history_file = os.path.expanduser("~/.history") + history_length = 100 + global_help = "" + + def __init__(self): + self.setup() + self.banner = "" + + def preceding(self): + """占位函数.在命令模块中覆盖此函数.可以预处理一些事情""" + pass + + def setup(self): + """ Initialization of third-party libraries + + Setting interpreter history. + Setting appropriate completer function. + + :return: + """ + if not os.path.exists(self.history_file): + with open(self.history_file, "a+") as history: + if is_libedit(): + history.write("_HiStOrY_V2_\n\n") + + readline.read_history_file(self.history_file) + readline.set_history_length(self.history_length) + atexit.register(readline.write_history_file, self.history_file) + + readline.parse_and_bind("set enable-keypad on") + + readline.set_completer(self.complete) + readline.set_completer_delims(" \t\n;") + if is_libedit(): + readline.parse_and_bind("bind ^I rl_complete") + else: + readline.parse_and_bind("tab: complete") + + def parse_line(self, line): + """ Split line into command and argument. + + :param line: line to parse + :return: (command, argument, named_arguments) + """ + kwargs = dict() + command, _, arg = line.strip().partition(" ") + args = arg.strip().split() + for word in args: + if '=' in word: + (key, value) = word.split('=', 1) + kwargs[key.lower()] = value + arg = arg.replace(word, '') + return command, ' '.join(arg.split()), kwargs + + @property + def prompt(self): + """ Returns prompt string """ + return ">>>" + + def get_command_handler(self, command): + """ Parsing command and returning appropriate handler. + + :param command: command + :return: command_handler + """ + try: + command_handler = getattr(self, "command_{}".format(command)) + except AttributeError: + raise SunhpcCliException("Unknown command: '{}'".format(command)) + + return command_handler + + def start(self): + """ Routersploit main entry point. Starting interpreter loop. """ + + print(self.banner) + self.preceding() + while True: + try: + command, args, kwargs = self.parse_line(input(self.prompt)) + if not command: + continue + command_handler = self.get_command_handler(command) + command_handler(args, **kwargs) + except (EOFError, KeyboardInterrupt, SystemExit): + print("Sunhpc cli stopped") + break + + def complete(self, text, state): + """Return the next possible completion for 'text'. + + If a command has not been entered, then complete against command list. + Otherwise try to call complete_ to get list of completions. + """ + if state == 0: + original_line = readline.get_line_buffer() + line = original_line.lstrip() + stripped = len(original_line) - len(line) + start_index = readline.get_begidx() - stripped + end_index = readline.get_endidx() - stripped + + if start_index > 0: + cmd, args, _ = self.parse_line(line) + if cmd == "": + complete_function = self.default_completer + else: + try: + complete_function = getattr(self, "complete_" + cmd) + except AttributeError: + complete_function = self.default_completer + else: + complete_function = self.raw_command_completer + + self.completion_matches = complete_function(text, line, start_index, end_index) + + try: + return self.completion_matches[state] + except IndexError: + return None + + def commands(self, *ignored): + """ Returns full list of interpreter commands. + + :param ignored: + :return: full list of interpreter commands + """ + return [command.rsplit("_").pop() for command in dir(self) if command.startswith("command_")] + + def raw_command_completer(self, text, line, start_index, end_index): + """ Complete command w/o any argument """ + return [command for command in self.suggested_commands() if command.startswith(text)] + + def default_completer(self, *ignored): + return [] + + def suggested_commands(self): + """ Entry point for intelligent tab completion. + + Overwrite this method to suggest suitable commands. + + :return: list of suitable commands + """ + return self.commands() + +class SunhpcInterpreter(BaseInterpreter): + history_file = os.path.expanduser("~/.rsf_history") + global_help = """Global commands: + help Print this help menu + use Select a module for usage + exec Execute a command in a shell + search Search for appropriate module + exit Exit RouterSploit""" + + module_help = """Module commands: + run Run the selected module with the given options + back De-select the current module + set