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 --- bin/completions-sunhpc.py | 31 +++ bin/sunhpc | 1 + data/.database | 2 +- data/sunhpc.db | Bin 94208 -> 94208 bytes etc/sunhpc.conf | 46 ++++ 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 +- sbin/sunhpc-completion-backup | 198 +++++++++++++++ var/nodes/database.xml | 0 11 files changed, 745 insertions(+), 8 deletions(-) create mode 100755 bin/completions-sunhpc.py create mode 100644 etc/sunhpc.conf create mode 100644 lib/sunhpc/commands/build/init/__init__.py create mode 100644 lib/sunhpc/core/interpreter.py create mode 100644 sbin/sunhpc-completion-backup create mode 100644 var/nodes/database.xml diff --git a/bin/completions-sunhpc.py b/bin/completions-sunhpc.py new file mode 100755 index 0000000..d2bd4b6 --- /dev/null +++ b/bin/completions-sunhpc.py @@ -0,0 +1,31 @@ +#!/opt/sunpy3/bin/python3 + +import os +import sys + + +cword = int(os.environ['COMP_CWORD']) +cwords = os.environ['COMP_WORDS'].split() +cline = os.environ['COMP_LINE'] +#curr = os.environ['COMP_CURR'] + +if 'sunhpc' in cwords: + cwords.remove('sunhpc') + + +commands = '/opt/sunhpc/lib/sunhpc/commands/' +modules = commands + '/'.join(cwords) +if os.path.exists(modules): + cmdpath = os.listdir(modules) +else: + cmdpath = os.listdir(commands) + +print (modules) +print ('-------------------------------') +print(' '.join(cmdpath)) +#print("candaidate1 candbidate2") + +#print ('\n-cword---%s---' % cword) +#print ('\n-cwords--%s---' % cwords) +#print ('\n-cline---%s---' % cline) +#print ('\n-curr----%s---' % sys.argv) diff --git a/bin/sunhpc b/bin/sunhpc index bab4e54..de4dac7 100755 --- a/bin/sunhpc +++ b/bin/sunhpc @@ -6,6 +6,7 @@ import sys import sunhpc import syslog import shutil +import readline import sunhpc.invoke if sys.getdefaultencoding() != 'utf-8': diff --git a/data/.database b/data/.database index 903daea..da5ac5d 100644 --- a/data/.database +++ b/data/.database @@ -1 +1 @@ -2023-04-16 08:28:49 +2023-10-12 18:44:23 diff --git a/data/sunhpc.db b/data/sunhpc.db index 4206300..933c343 100644 Binary files a/data/sunhpc.db and b/data/sunhpc.db differ diff --git a/etc/sunhpc.conf b/etc/sunhpc.conf new file mode 100644 index 0000000..b1c57ac --- /dev/null +++ b/etc/sunhpc.conf @@ -0,0 +1,46 @@ +# +# sunhpc cluster config file. +# +country CN +state LiaoNing +city DaLian +url https://www.sunhpc.com +name Sunhpc-cluster +contact info@sunhpc.com +worksdir /export +distrodir /export/sunhpc +partition default +safeport 372 +safedirs safe.d +safesecurity safe-security +publichostname cluster.sunhpc.com +publicinterface eth0 +publicaddress 172.16.1.1 +publicgateway 172.16.1.1 +publicnetmask 255.255.255.0 +publicdnsserver 223.5.5.5 +publicmacaddress B8:CA:3A:A8:C5:D3 +publiccidr 24 +publicnetwork 172.16.1.0 +publicdomain sunhpc.com +publicmtu 1500 +publicntphost pool.ntp.org +privatehostname cluster +privateinterface wlan0 +privateaddress 192.168.199.146 +privatenetmask 255.255.255.0 +privatemacaddress 00:21:6A:A7:D5:62 +privatecidr 24 +privatenetwork 192.168.199.0 +privatedomain local +privatemtu 1500 +privatentphost cluster.local +timezone Asia/Shanghai +bootargs net.ifnames=0 biosdevname=0 ksdevice=bootif +basedir install +ganglia 224.0.0.3 +nextserver 192.168.199.146 +plugin_port 12345 +pxefilename pxelinux.0 +pxelinuxdir /tftpboot/pxelinux +distribution sunhpc-dist 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