return r.json().get("text", None) def remove_question(message): s = sent_tokenize(message) return " ".join([x for x in s if "?" not in x]) def send_message(message): start = time.time() response = converse(message) try: refactored_response = remove_question(message) except: pass response_time = time.time() - start with open("conversation.txt", "a+") as fh: fh.write( f"{response_time}\n{message}\n{response}\n{refactored_response}\n\n" ) return bot_template.format(response) while 1: input = prompt( "CHANDRA: ", history=FileHistory("history.txt"), auto_suggest=AutoSuggestFromHistory(), ) print(send_message(input), "\n")
def handle_fcomm_command(command, user, randomuri, implant_id): # convert randomuri to parent randomuri oldrandomuri = randomuri p = get_implantdetails(randomuri) newimplant_id = re.search(r'(?<=\s)\S*', p.Label).group() if newimplant_id is not None: randomuri = get_randomuri(newimplant_id) # alias mapping for alias in cs_alias: if alias[0] == command[:len(command.rstrip())]: command = alias[1] # alias replace for alias in cs_replace: if command.startswith(alias[0]): command = command.replace(alias[0], alias[1]) original_command = command command = command.strip() run_autoloads_sharp(command, randomuri, user, loadmodule_command="fcomm-loadmodule") if command.startswith("searchhistory"): searchterm = (command).replace("searchhistory ", "") with open('%s/.implant-history' % PoshProjectDirectory) as hisfile: for line in hisfile: if searchterm in line.lower(): print(Colours.PURPLE + line.replace("+", "")) elif command.startswith("searchhelp"): searchterm = (command).replace("searchhelp ", "") helpful = sharp_help.split('\n') for line in helpful: if searchterm in line.lower(): print(Colours.PURPLE + line) elif command.startswith("upload-file"): source = "" destination = "" if command == "upload-file": style = Style.from_dict({ '': '#772953', }) 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("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: ") else: args = argp(command) source = args.source destination = args.destination try: destination = destination.replace("\\", "\\\\") print("") print("Uploading %s to %s" % (source, destination)) uploadcommand = f"upload-file {source} {destination}" new_task(f"fcomm-command {uploadcommand}", user, randomuri) except Exception as e: print_bad("Error with source file: %s" % e) traceback.print_exc() elif command.startswith("unhide-implant"): unhide_implant(oldrandomuri) elif command.startswith("hide-implant"): kill_implant(oldrandomuri) elif command.startswith("inject-shellcode"): params = re.compile("inject-shellcode", re.IGNORECASE) params = params.sub("", command) style = Style.from_dict({ '': '#772953', }) session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Location of shellcode file: ", completer=FilePathCompleter( PayloadsDirectory, glob="*.bin")) path = PayloadsDirectory + path except KeyboardInterrupt: return try: shellcodefile = load_file(path) if shellcodefile is not None: new_task( "fcomm-command run-exe Core.Program Core Inject-Shellcode %s%s #%s" % (base64.b64encode(shellcodefile).decode("utf-8"), params, os.path.basename(path)), user, randomuri) except Exception as e: print("Error loading file: %s" % e) elif command.startswith("migrate"): params = re.compile("migrate", re.IGNORECASE) params = params.sub("", command) migrate(randomuri, user, params) elif command == "kill-implant" or command == "exit": impid = get_implantdetails(randomuri) ri = input( "Are you sure you want to terminate the implant ID %s? (Y/n) " % impid.ImplantID) if ri.lower() == "n": print("Implant not terminated") if ri == "" or ri.lower() == "y": new_task("fcomm-kill", user, randomuri) kill_implant(oldrandomuri) elif command == "sharpsocks": from random import choice allchar = string.ascii_letters channel = "".join(choice(allchar) for x in range(25)) sharpkey = gen_key().decode("utf-8") sharpurls = get_sharpurls() sharpurls = sharpurls.split(",") sharpurl = select_item("HostnameIP", "C2Server") print( PoshInstallDirectory + "SharpSocks/SharpSocksServerCore -c=%s -k=%s --verbose -l=%s\r\n" % (channel, sharpkey, SocksHost) + Colours.PURPLE) ri = input( "Are you ready to start the SharpSocks in the implant? (Y/n) ") if ri.lower() == "n": print("") if ri == "": new_task( "fcomm-command run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken" % (sharpurl, channel, sharpkey, sharpurls[0].replace( "\"", ""), sharpurls[1].replace("\"", "")), user, randomuri) if ri.lower() == "y": new_task( "fcomm-command run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken" % (sharpurl, channel, sharpkey, sharpurls[0].replace( "\"", ""), sharpurls[1].replace("\"", "")), user, randomuri) elif (command.startswith("stop-keystrokes")): new_task( "fcomm-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri) update_label("", randomuri) elif (command.startswith("start-keystrokes")): check_module_loaded("Logger.exe", randomuri, user) new_task( "fcomm-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri) update_label("KEYLOG", randomuri) elif (command.startswith("get-keystrokes")): new_task( "fcomm-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri) elif (command.startswith("get-screenshotmulti")): pwrStatus = get_powerstatusbyrandomuri(randomuri) if (pwrStatus is not None and pwrStatus[7]): ri = input( "[!] Screen is reported as LOCKED, do you still want to attempt a screenshot? (y/N) " ) if ri.lower() == "n" or ri.lower() == "": return new_task(f"fcomm-command {command}", user, randomuri) update_label("SCREENSHOT", randomuri) elif (command.startswith("get-screenshot")): pwrStatus = get_powerstatusbyrandomuri(randomuri) if (pwrStatus is not None and pwrStatus[7]): ri = input( "[!] Screen is reported as LOCKED, do you still want to attempt a screenshot? (y/N) " ) if ri.lower() == "n" or ri.lower() == "": return new_task(f"fcomm-command {command}", user, randomuri) elif (command == "get-powerstatus"): getpowerstatus(randomuri) new_task( "fcomm-command run-dll PwrStatusTracker.PwrFrm PwrStatusTracker GetPowerStatusResult ", user, randomuri) elif (command == "getpowerstatus"): getpowerstatus(randomuri) new_task( "fcomm-command run-dll PwrStatusTracker.PwrFrm PwrStatusTracker GetPowerStatusResult ", user, randomuri) elif (command.startswith("stop-powerstatus")): new_task(f"fcomm-command {command}", user, randomuri) update_label("", randomuri) elif (command.startswith("stoppowerstatus")): new_task(f"fcomm-command {command}", user, randomuri) update_label("", randomuri) elif (command.startswith("pslo")): new_task(f"fcomm-{command}", user, randomuri) elif (command.startswith("run-exe SharpWMI.Program") ) and "execute" in command and "payload" not in command: style = Style.from_dict({'': '#772953'}) 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("fcomm-command %s payload=%s" % (command, payload), user, randomuri) else: print_bad("Could not find file") elif (command.startswith("get-hash")): check_module_loaded("InternalMonologue.exe", randomuri, user) new_task( "fcomm-command run-exe InternalMonologue.Program InternalMonologue", user, randomuri) elif (command.startswith("safetykatz")): new_task("fcomm-command run-exe SafetyKatz.Program %s" % command, user, randomuri) elif command.startswith("loadmoduleforce"): params = re.compile("loadmoduleforce ", re.IGNORECASE) params = params.sub("", command) new_task("fcomm-loadmodule %s" % params, user, randomuri) elif command.startswith("loadmodule"): params = re.compile("loadmodule ", re.IGNORECASE) params = params.sub("", command) new_task("fcomm-loadmodule %s" % params, user, randomuri) elif command.startswith("listmodules"): modules = os.listdir("%s/Modules/" % PoshInstallDirectory) modules = sorted(modules, key=lambda s: s.lower()) print("") print("[+] Available modules:") print("") for mod in modules: if (".exe" in mod) or (".dll" in mod): print(mod) elif command.startswith("modulesloaded"): ml = get_implantdetails(randomuri) print(ml.ModsLoaded) new_task("fcomm-command listmodules", user, randomuri) elif command == "help" or command == "?": print(sharp_help) elif command.startswith("beacon") or command.startswith( "set-beacon") or command.startswith("setbeacon"): new_sleep = command.replace('set-beacon ', '') new_sleep = new_sleep.replace('setbeacon ', '') new_sleep = new_sleep.replace('beacon ', '').strip() if not validate_sleep_time(new_sleep): print(Colours.RED) print( "Invalid sleep command, please specify a time such as 50s, 10m or 1h" ) print(Colours.PURPLE) else: new_task(f"fcomm-command {command}", user, randomuri) else: if command: new_task(f"fcomm-command {original_command}", user, randomuri) return
def interactive(self, scope=None): import platform from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from topic_model.lda import TopicInferer, DEFAULT_SEPARATOR from util.nlp import NLPToolkit nlp_toolkit = NLPToolkit() __os = platform.system() self.config.infer_batch_size = 1 self._pre_model_creation() if self.config.lda_model_dir is not None: topic_inferer = TopicInferer(self.config.lda_model_dir) else: topic_inferer = None infer_model = self._get_model_helper().create_infer_model(self.config, scope) with tf.Session( config=model_helper.get_config_proto(self.config.log_device), graph=infer_model.graph) as sess: latest_ckpt = tf.train.latest_checkpoint(self.config.model_dir) loaded_infer_model = model_helper.load_model( infer_model.model, latest_ckpt, sess, "infer") log.print_out("# Start decoding") if __os == 'Windows': sentence = input("> ").strip() else: sentence = prompt(">>> ", history=FileHistory(os.path.join(self.config.model_dir, ".chat_history"))).strip() conversation = [vocab.EOS] * (self.config.num_turns - 1) while sentence: current_utterance = ' '.join(nlp_toolkit.tokenize(sentence)).lower() conversation.append(current_utterance) conversation.pop(0) feedable_context = "\t".join(conversation) if topic_inferer is None: iterator_feed_dict = { infer_model.src_placeholder: [feedable_context], infer_model.batch_size_placeholder: 1, } else: topic_words = topic_inferer.from_collection([feedable_context], dialogue_as_doc=True, words_per_topic=self.config.topic_words_per_utterance) iterator_feed_dict = { infer_model.src_placeholder: [feedable_context + DEFAULT_SEPARATOR + " ".join(topic_words)], infer_model.batch_size_placeholder: 1, } sess.run(infer_model.iterator.initializer, feed_dict=iterator_feed_dict) output, infer_summary = loaded_infer_model.decode(sess) if self.config.beam_width > 0 and self._consider_beam(): # get the top translation. output = output[0] resp = ncm_utils.get_translation(output, sent_id=0) log.print_out(resp + b"\n") if __os == 'Windows': sentence = input("> ").strip() else: sentence = prompt(">>> ", history=FileHistory(os.path.join(self.config.model_dir, ".chat_history"))).strip() print("Bye!!!")
def run_cli(self): self.iterations = 0 self.configure_pager() self.refresh_completions() history_file = os.path.expanduser(self.config['main']['history_file']) history = FileHistory(history_file) self.cli = self._build_cli(history) def one_iteration(): document = self.cli.run() special.set_expanded_output(False) try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: LOGGER.error("sql: %r, error: %r", document.text, e) LOGGER.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg='red') return if not document.text.strip(): return if self.destructive_warning: destroy = confirm_destructive_query(document.text) if destroy is None: pass # Query was not destructive. Nothing to do here. elif destroy is True: self.echo('Your call!') else: self.echo('Wise choice!') return mutating = False try: LOGGER.debug('sql: %r', document.text) special.write_tee(self.get_prompt(self.prompt) + document.text) successful = False start = time() res = self.sqlexecute.run(document.text) successful = True threshold = 1000 result_count = 0 for title, rows, headers, status in res: if rows and len(rows) > threshold: self.echo( 'The result set has more than {} rows.'.format( threshold), fg='red') if not confirm('Do you want to continue?'): self.echo('Aborted!', err=True, fg='red') break formatted = self.format_output( title, rows, headers, special.is_expanded_output(), None) t = time() - start try: if result_count > 0: self.echo('') try: self.output(formatted, status) except KeyboardInterrupt: pass if special.is_timing_enabled(): self.echo('Time: %0.03fs' % t) except KeyboardInterrupt: pass start = time() result_count += 1 mutating = mutating or is_mutating(status) special.unset_once_if_written() except EOFError as e: raise e except KeyboardInterrupt: pass except NotImplementedError: self.echo('Not Yet Implemented.', fg="yellow") except OperationalError as e: LOGGER.debug("Exception: %r", e) LOGGER.error("sql: %r, error: %r", document.text, e) LOGGER.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg='red') except Exception as e: LOGGER.error("sql: %r, error: %r", document.text, e) LOGGER.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg='red') else: # Refresh the table names and column names if necessary. if need_completion_refresh(document.text): LOGGER.debug("=" * 10) self.refresh_completions() query = Query(document.text, successful, mutating) self.query_history.append(query) try: while True: one_iteration() self.iterations += 1 except EOFError: special.close_tee()
def cli(): """This script showcases different terminal UI helpers in Click.""" prompt_kwargs = { 'history': FileHistory('./hsitory.txt'), } repl(click.get_current_context(), prompt_kwargs=prompt_kwargs)
print("[*] Listening on %s:%d." % (bindAddress, localport)) cltSkt, clientAddr = lstnSkt.accept() cltIp = clientAddr[0] print("[*] Incoming connection from %s." % cltIp) print("[i] Type %chonker-exit at any prompt to quit Chonker.") rsock, ssock = socket.socketpair() t1 = threading.Thread(target=listenerThrd, args=(rsock, cltSkt)) t1.start() # Free listening socket lstnSkt.close() # Prompt settings promptSession = PromptSession(history=FileHistory(historyFile)) style = Style.from_dict({ '': '#ff0066', # User input (default text). 'prompt': '#aa22ff', # Prompt. }) promptMessage = [ ('class:prompt', promptStr), ] while True: #with patch_stdout(): if True: cmd = promptSession.prompt(promptMessage, auto_suggest=AutoSuggestFromHistory(), style=style) ssock.sendall(cmd.encode())
def __init__(self, context): self.context = context self.session = PromptSession("%s> " % self.name, history=FileHistory( self._history_filename()), auto_suggest=AutoSuggestFromHistory())
def __init__(self, cli_ctx, style=None, completer=None, lexer=None, history=None, input_custom=sys.stdin, output_custom=None, user_feedback=False, intermediate_sleep=.25, final_sleep=4): from .color_styles import style_factory self.cli_ctx = cli_ctx self.config = Configuration(cli_ctx.config, style=style) self.config.set_style(style) self.style = style_factory(self.config.get_style()) try: gathered_commands = GatherCommands(self.config) self.completer = completer or AzCompleter(self, gathered_commands) self.completer.initialize_command_table_attributes() self.lexer = lexer or get_az_lexer(gathered_commands) except IOError: # if there is no cache self.completer = AzCompleter(self, None) self.lexer = None self.history = history or FileHistory( os.path.join(self.config.get_config_dir(), self.config.get_history())) if os.environ.get(_ENV_ADDITIONAL_USER_AGENT): os.environ[ _ENV_ADDITIONAL_USER_AGENT] += ' AZURECLISHELL/' + VERSION else: os.environ[_ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + VERSION # OH WHAT FUN TO FIGURE OUT WHAT THESE ARE! self._cli = None self.layout = None self.description_docs = u'' self.param_docs = u'' self.example_docs = u'' self.last = None self.last_exit = 0 self.user_feedback = user_feedback self.input = input_custom self.output = output_custom self.config_default = "" self.default_command = "" self.threads = [] self.curr_thread = None self.spin_val = -1 self.intermediate_sleep = intermediate_sleep self.final_sleep = final_sleep self.command_table_thread = None # try to consolidate state information here... # Used by key bindings and layout self.example_page = 1 self.is_prompting = False self.is_example_repl = False self.is_showing_default = False self.is_symbols = True
def __init__( self, get_globals=None, get_locals=None, history_filename=None, vi_mode=False, # For internal use. _completer=None, _validator=None, _lexer=None, _extra_buffers=None, _extra_buffer_processors=None, _on_start=None, _extra_layout_body=None, _extra_toolbars=None, _input_buffer_height=None, _accept_action=AcceptAction.RETURN_DOCUMENT, _on_exit=AbortAction.RAISE_EXCEPTION): self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self._completer = _completer or PythonCompleter( self.get_globals, self.get_locals) self._validator = _validator or PythonValidator( self.get_compiler_flags) self.history = FileHistory( history_filename) if history_filename else InMemoryHistory() self._lexer = _lexer or PygmentsLexer(PythonLexer) self._extra_buffers = _extra_buffers self._accept_action = _accept_action self._on_exit = _on_exit self._on_start = _on_start self._input_buffer_height = _input_buffer_height self._extra_layout_body = _extra_layout_body or [] self._extra_toolbars = _extra_toolbars or [] self._extra_buffer_processors = _extra_buffer_processors or [] # Settings. self.show_signature = False self.show_docstring = False self.show_meta_enter_message = True self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN self.completion_menu_scroll_offset = 1 self.show_line_numbers = False self.show_status_bar = True self.wrap_lines = True self.complete_while_typing = True self.vi_mode = vi_mode self.paste_mode = False # When True, don't insert whitespace after newline. self.confirm_exit = True # Ask for confirmation when Control-D is pressed. self.accept_input_on_enter = 2 # Accept when pressing Enter 'n' times. # 'None' means that meta-enter is always required. self.enable_open_in_editor = True self.enable_system_bindings = True self.enable_input_validation = True self.enable_auto_suggest = False self.enable_mouse_support = False self.enable_history_search = False # When True, like readline, going # back in history will filter the # history on the records starting # with the current input. self.highlight_matching_parenthesis = False self.show_sidebar = False # Currently show the sidebar. self.show_sidebar_help = True # When the sidebar is visible, also show the help text. self.show_exit_confirmation = False # Currently show 'Do you really want to exit?' self.terminal_title = None # The title to be displayed in the terminal. (None or string.) self.exit_message = 'Do you really want to exit?' self.insert_blank_line_after_output = True # (For the REPL.) # Tokens to be shown at the prompt. self.prompt_style = 'classic' # The currently active style. self.all_prompt_styles = { # Styles selectable from the menu. 'ipython': IPythonPrompt(self), 'classic': ClassicPrompt(), } self.get_input_prompt_tokens = lambda cli: \ self.all_prompt_styles[self.prompt_style].in_tokens(cli) self.get_output_prompt_tokens = lambda cli: \ self.all_prompt_styles[self.prompt_style].out_tokens(cli) #: Load styles. self.code_styles = get_all_code_styles() self.ui_styles = get_all_ui_styles() self._current_code_style_name = 'default' self._current_ui_style_name = 'default' if is_windows(): self._current_code_style_name = 'win32' self._current_style = self._generate_style() self.true_color = False # Options to be configurable from the sidebar. self.options = self._create_options() self.selected_option_index = 0 #: Incremeting integer counting the current statement. self.current_statement_index = 1 # Code signatures. (This is set asynchronously after a timeout.) self.signatures = [] # Use a KeyBindingManager for loading the key bindings. self.key_bindings_manager = KeyBindingManager( enable_abort_and_exit_bindings=True, enable_search=True, enable_vi_mode=Condition(lambda cli: self.vi_mode), enable_open_in_editor=Condition( lambda cli: self.enable_open_in_editor), enable_system_bindings=Condition( lambda cli: self.enable_system_bindings), enable_auto_suggest_bindings=Condition( lambda cli: self.enable_auto_suggest), # Disable all default key bindings when the sidebar or the exit confirmation # are shown. enable_all=Condition(lambda cli: not (self.show_sidebar or self. show_exit_confirmation))) load_python_bindings(self.key_bindings_manager, self) load_sidebar_bindings(self.key_bindings_manager, self) load_confirm_exit_bindings(self.key_bindings_manager, self) # Boolean indicating whether we have a signatures thread running. # (Never run more than one at the same time.) self._get_signatures_thread_running = False
def userInterface(): global continueFlag completer = WordCompleter([ 'register', 'get_rooms', 'show_rooms', 'show_errors', 'add', 'join', 'leave', 'disconnect', 'read', 'send', 'get_members', 'show_members', 'exit' ], ignore_case=True) while continueFlag: userInput = prompt('IRC>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=completer) args = userInput.split(" ", 2) toSend = [] # Strings to be send to the server. # Assign a user name to the connection if args[0] == "register" and len(args) == 2: toSend.append("REGISTER UNIQUE " + args[1]) # Ask the server for a list of chat rooms elif args[0] == "get_rooms": toSend.append("LIST ROOMS") # Join a room elif args[0] == "join" and len(args) == 2: rooms = args[1].split(',') for room in rooms: toSend.append("JOIN_ROOM " + room) # Create a new room elif args[0] == "add" and len(args) == 2: rooms = args[1].split(',') for room in rooms: toSend.append("CREATE_ROOM " + room) # Leave a room elif args[0] == "leave" and len(args) == 2: rooms = args[1].split(',') for room in rooms: toSend.append("LEAVE_ROOM " + room) # Send a message to a room(s) elif args[0] == "send" and len(args) == 3: for room in args[1].split(','): toSend.append("SEND_MSG " + room + " " + args[2]) # Terminate connection with server elif args[0] == "disconnect": toSend.append("DISCONNECT ALL") continueFlag = False # Ask the server for the list of members in a room elif args[0] == 'get_members' and len(args) == 2: toSend.append("LIST_ROOM_MEMBERS " + args[1]) # Opreations that do not require the server elif args[0] == "show_rooms": for room in chatHistory.keys(): print(room) continue # Display memembers of a certain chat room. elif args[0] == "show_members": room = args[1] if room in chatHistory.keys(): for msg in chatHistory[room].members: print(msg) else: print("Error: Room is not valid") continue # Read messages from specfici rooms elif args[0] == "read": room = args[1] if room in chatHistory.keys(): if len(args) != 3 or (not args[2] in ["ALL", "UNREAD"]): print("Error: expected third paramters ALL|UNREAD") continue msgs = [] if args[2] == "ALL": msgs = chatHistory[room].messages else: msgs = chatHistory[room].readUnreadMessages() for msg in msgs: print(msg) else: print("Error: Room is not valid") continue # Displays errors recieved by the server elif args[0] == "show_errors": for msg in errorLog.readUnreadMessages(): print(msg) continue # User is done elif args[0] == 'exit': continueFlag = False sys.exit() # Client side only commands will continue, so they will not reach here. if toSend == []: print("ERROR with commmand: " + userInput) # Each command creates some number of requests to be sent to the server. for msg in toSend: formatted = msg + '\0' server.sendall(formatted.encode('utf-8'))
def reset_history(self): history_file_path = os.path.join(self.config.get_config_dir(), self.config.get_history()) os.remove(history_file_path) self.history = FileHistory(history_file_path) self.cli.buffers[DEFAULT_BUFFER].history = self.history
rcon_password = '******' # http://devhumor.com/content/uploads/images/November2016/optimism.jpg async def main_loop(): global get_input async with websockets.connect(bakkes_server) as websocket: await websocket.send('rcon_password ' + rcon_password) auth_status = await websocket.recv() assert auth_status == 'authyes' while True: try: line = get_input() except EOFError as e: return except KeyboardInterrupt as e: print() continue await websocket.send(line) if __name__ == '__main__': arguments = docopt(__doc__, version='BakkesMod REPL 1.0') if arguments['--silent']: get_input = input else: history = FileHistory('.bakkes_repl_history.txt') get_input = lambda: prompt('bakkes> ', history=history) asyncio.get_event_loop().run_until_complete(main_loop())
def __init__(self, config_directory='~/.pyvim', input=None, output=None): self.input = input self.output = output # Vi options. self.show_line_numbers = True self.highlight_search = True self.paste_mode = False self.show_ruler = True self.show_wildmenu = True self.expand_tab = True # Insect spaces instead of tab characters. self.tabstop = 4 # Number of spaces that a tab character represents. self.incsearch = True # Show matches while typing search string. self.ignore_case = False # Ignore case while searching. self.enable_mouse_support = True self.display_unprintable_characters = True # ':set list' self.enable_jedi = True # ':set jedi', for Python Jedi completion. self.scroll_offset = 0 # ':set scrolloff' self.relative_number = False # ':set relativenumber' self.wrap_lines = True # ':set wrap' self.break_indent = False # ':set breakindent' self.cursorline = False # ':set cursorline' self.cursorcolumn = False # ':set cursorcolumn' self.colorcolumn = [] # ':set colorcolumn'. List of integers. # Ensure config directory exists. self.config_directory = os.path.abspath(os.path.expanduser(config_directory)) if not os.path.exists(self.config_directory): os.mkdir(self.config_directory) self.window_arrangement = WindowArrangement(self) self.message = None # Load styles. (Mapping from name to Style class.) self.styles = generate_built_in_styles() self.current_style = get_editor_style_by_name('vim') # I/O backends. self.io_backends = [ DirectoryIO(), HttpIO(), GZipFileIO(), # Should come before FileIO. FileIO(), ] # Create history and search buffers. def handle_action(buff): ' When enter is pressed in the Vi command line. ' text = buff.text # Remember: leave_command_mode resets the buffer. # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. self.leave_command_mode(append_to_history=True) # Execute command. handle_command(self, text) commands_history = FileHistory(os.path.join(self.config_directory, 'commands_history')) self.command_buffer = Buffer( accept_handler=handle_action, enable_history_search=True, completer=create_command_completer(self), history=commands_history, multiline=False) search_buffer_history = FileHistory(os.path.join(self.config_directory, 'search_history')) self.search_buffer = Buffer( history=search_buffer_history, enable_history_search=True, multiline=False) # Create key bindings registry. self.key_bindings = create_key_bindings(self) # Create layout and CommandLineInterface instance. self.editor_layout = EditorLayout(self, self.window_arrangement) self.application = self._create_application() # Hide message when a key is pressed. def key_pressed(_): self.message = None self.application.key_processor.before_key_press += key_pressed # Command line previewer. self.previewer = CommandPreviewer(self) self.last_substitute_text = ''
class PromptInterface(object): go_on = True _walletdb_loop = None Wallet = None _known_things = [] commands = [ 'quit', 'help', 'block {index/hash} (tx)', 'header {index/hash}', 'tx {hash}', 'asset {assetId}', 'asset search {query}', 'contract {contract hash}', 'contract search {query}', 'notifications {block_number or address}', 'mem', 'nodes', 'state', 'config debug {on/off}', 'config sc-events {on/off}', 'build {path/to/file.py} (test {params} {returntype} {needs_storage} {needs_dynamic_invoke} {test_params})', 'load_run {path/to/file.avm} (test {params} {returntype} {needs_storage} {needs_dynamic_invoke} {test_params})', 'import wif {wif}', 'import nep2 {nep2_encrypted_key}', 'import contract {path/to/file.avm} {params} {returntype} {needs_storage} {needs_dynamic_invoke}', 'import contract_addr {contract_hash} {pubkey}', 'import watch_addr {address}', 'import token {token_contract_hash}', 'export wif {address}', 'export nep2 {address}', 'open wallet {path}', 'create wallet {path}', 'wallet {verbose}', 'wallet claim', 'wallet migrate', 'wallet rebuild {start block}', 'wallet delete_addr {addr}', 'wallet alias {addr} {title}', 'wallet tkn_send {token symbol} {address_from} {address to} {amount} ', 'wallet tkn_send_from {token symbol} {address_from} {address to} {amount}', 'wallet tkn_send_blog {token symbol} {address_from} {address to} {amount}', 'wallet tkn_approve {token symbol} {address_from} {address to} {amount}', 'wallet tkn_allowance {token symbol} {address_from} {address to}', 'wallet tkn_mint {token symbol} {mint_to_addr} (--attach-neo={amount}, --attach-gas={amount})', 'wallet unspent', 'wallet close', 'withdraw_request {asset_name} {contract_hash} {to_addr} {amount}', 'withdraw holds # lists all current holds', 'withdraw completed # lists completed holds eligible for cleanup', 'withdraw cancel # cancels current holds', 'withdraw cleanup # cleans up completed holds', 'withdraw # withdraws the first hold availabe', 'withdraw all # withdraw all holds available', 'send {assetId or name} {address} {amount} (--from-addr={addr})', 'sign {transaction in JSON format}', 'testinvoke {contract hash} {params} (--attach-neo={amount}, --attach-gas={amount})', 'debugstorage {on/off/reset}' ] history = FileHistory(FILENAME_PROMPT_HISTORY) token_style = None start_height = None start_dt = None def __init__(self): self.input_parser = InputParser() self.start_height = Blockchain.Default().Height self.start_dt = datetime.datetime.utcnow() self.token_style = style_from_dict({ Token.Command: preferences.token_style['Command'], Token.Neo: preferences.token_style['Neo'], Token.Default: preferences.token_style['Default'], Token.Number: preferences.token_style['Number'], }) def get_bottom_toolbar(self, cli=None): out = [] try: out = [(Token.Command, '[%s] Progress: ' % settings.net_name), (Token.Number, str(Blockchain.Default().Height)), (Token.Neo, '/'), (Token.Number, str(Blockchain.Default().HeaderHeight))] except Exception as e: pass return out def get_completer(self): standard_completions = [ 'block', 'tx', 'header', 'mem', 'neo', 'gas', 'help', 'state', 'nodes', 'exit', 'quit', 'config', 'import', 'export', 'open', 'wallet', 'contract', 'asset', 'wif', 'watch_addr', 'contract_addr', 'testinvoke', 'tkn_send', 'tkn_mint', 'tkn_send_from', 'tkn_send_blog', 'tkn_approve', 'tkn_allowance', 'build', 'notifications', ] if self.Wallet: for addr in self.Wallet.Addresses: if addr not in self._known_things: self._known_things.append(addr) for alias in self.Wallet.NamedAddr: if alias.Title not in self._known_things: self._known_things.append(alias.Title) for tkn in self.Wallet.GetTokens().values(): if tkn.symbol not in self._known_things: self._known_things.append(tkn.symbol) all_completions = standard_completions + self._known_things completer = WordCompleter(all_completions) return completer def quit(self): print('Shutting down. This may take a bit...') self.go_on = False self.do_close_wallet() reactor.stop() def help(self): tokens = [] for c in self.commands: tokens.append((Token.Command, "%s\n" % c)) print_tokens(tokens, self.token_style) def do_open(self, arguments): if self.Wallet: self.do_close_wallet() item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if not os.path.exists(path): print("Wallet file not found") return passwd = prompt("[password]> ", is_password=True) password_key = to_aes_key(passwd) try: self.Wallet = UserWallet.Open(path, password_key) self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) print("Opened wallet at %s" % path) except Exception as e: print("Could not open wallet: %s" % e) else: print("Please specify a path") else: print("Please specify something to open") def do_create(self, arguments): item = get_arg(arguments) if item and item == 'wallet': path = get_arg(arguments, 1) if path: if os.path.exists(path): print("File already exists") return passwd1 = prompt("[password]> ", is_password=True) passwd2 = prompt("[password again]> ", is_password=True) if passwd1 != passwd2 or len(passwd1) < 10: print( "Please provide matching passwords that are at least 10 characters long" ) return password_key = to_aes_key(passwd1) try: self.Wallet = UserWallet.Create(path=path, password=password_key) contract = self.Wallet.GetDefaultContract() key = self.Wallet.GetKey(contract.PublicKeyHash) print("Wallet %s" % json.dumps(self.Wallet.ToJson(), indent=4)) print("Pubkey %s" % key.PublicKey.encode_point(True)) except Exception as e: print("Exception creating wallet: %s" % e) self.Wallet = None if os.path.isfile(path): try: os.remove(path) except Exception as e: print("Could not remove {}: {}".format(path, e)) return if self.Wallet: self._walletdb_loop = task.LoopingCall( self.Wallet.ProcessBlocks) self._walletdb_loop.start(1) else: print("Please specify a path") def do_close_wallet(self): if self.Wallet: path = self.Wallet._path self._walletdb_loop.stop() self._walletdb_loop = None self.Wallet.Close() self.Wallet = None print("Closed wallet %s" % path) def do_import(self, arguments): item = get_arg(arguments) if not item: print("Please specify something to import") return if item == 'wif': if not self.Wallet: print("Please open a wallet before importing WIF") return wif = get_arg(arguments, 1) if not wif: print("Please supply a valid WIF key") return try: prikey = KeyPair.PrivateKeyFromWIF(wif) key = self.Wallet.CreateKey(prikey) print("Imported key: %s" % wif) print("Pubkey: %s\n" % key.PublicKey.encode_point(True).hex()) print("Wallet: %s" % json.dumps(self.Wallet.ToJson(), indent=4)) except ValueError as e: print(str(e)) except Exception as e: print(str(e)) return elif item == 'nep2': if not self.Wallet: print("Please open a wallet before importing a NEP2 key") return nep2_key = get_arg(arguments, 1) if not nep2_key: print("Please supply a valid NEP2 encrypted private key") return nep2_passwd = prompt("[key password]> ", is_password=True) try: prikey = KeyPair.PrivateKeyFromNEP2(nep2_key, nep2_passwd) key = self.Wallet.CreateKey(prikey) print("Imported NEP2 key: %s" % nep2_key) print("Pubkey: %s\n" % key.PublicKey.encode_point(True).hex()) print("Wallet: %s" % json.dumps(self.Wallet.ToJson(), indent=4)) except ValueError as e: print(str(e)) except Exception as e: print(str(e)) return elif item == 'contract': return self.load_smart_contract(arguments) elif item == 'contract_addr': return ImportContractAddr(self.Wallet, arguments[1:]) elif item == 'watch_addr': return ImportWatchAddr(self.Wallet, get_arg(arguments, 1)) elif item == 'multisig_addr': return ImportMultiSigContractAddr(self.Wallet, arguments[1:]) elif item == 'token': return ImportToken(self.Wallet, get_arg(arguments, 1)) else: print("Import of '%s' not implemented" % item) def do_build(self, arguments): BuildAndRun(arguments, self.Wallet) def do_load_n_run(self, arguments): LoadAndRun(arguments, self.Wallet) def do_export(self, arguments): item = get_arg(arguments) if item == 'wif': if not self.Wallet: return print("Please open a wallet") address = get_arg(arguments, 1) if not address: return print("Please specify an address") passwd = prompt("[wallet password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") keys = self.Wallet.GetKeys() for key in keys: if key.GetAddress() == address: export = key.Export() print("WIF key export: %s" % export) return elif item == 'nep2': if not self.Wallet: return print("Please open a wallet") address = get_arg(arguments, 1) if not address: return print("Please specify an address") passwd = prompt("[wallet password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") nep2_passwd1 = prompt("[key password]> ", is_password=True) if len(nep2_passwd1) < 10: return print( "Please provide a password with at least 10 characters") nep2_passwd2 = prompt("[key password again]> ", is_password=True) if nep2_passwd1 != nep2_passwd2: return print("Passwords do not match") keys = self.Wallet.GetKeys() for key in keys: export = key.ExportNEP2(nep2_passwd1) print("NEP2 key export: %s" % export) return print("Command export %s not found" % item) def make_withdraw_request(self, arguments): if not self.Wallet: print("Please open a wallet") return if len(arguments) == 4: RequestWithdrawFrom(self.Wallet, arguments[0], arguments[1], arguments[2], arguments[3]) else: print( "Incorrect arg length. Use 'withdraw_request {asset_id} {contract_hash} {to_addr} {amount}'" ) def do_withdraw(self, arguments): if not self.Wallet: print("Please open a wallet") return item = get_arg(arguments, 0) if item: if item == 'holds': PrintHolds(self.Wallet) elif item == 'delete_holds': index_to_delete = -1 if get_arg(arguments, 1) and int(get_arg(arguments, 1)) > -1: index_to_delete = int(get_arg(arguments, 1)) DeleteHolds(self.Wallet, index_to_delete) elif item == 'cancel_holds': if len(arguments) > 1: CancelWithdrawalHolds(self.Wallet, get_arg(arguments, 1)) else: print("Please specify contract hash to cancel holds for") elif item == 'completed': ShowCompletedHolds(self.Wallet) elif item == 'cleanup': CleanupCompletedHolds(self.Wallet) elif item == 'all': WithdrawAll(self.Wallet) else: WithdrawOne(self.Wallet) def do_notifications(self, arguments): if NotificationDB.instance() is None: print("No notification DB Configured") return item = get_arg(arguments, 0) events = [] if len(item) == 34: addr = item events = NotificationDB.instance().get_by_addr(addr) else: try: block_height = int(item) if block_height < Blockchain.Default().Height: events = NotificationDB.instance().get_by_block( block_height) else: print("Block %s not found" % block_height) return except Exception as e: print("Could not parse block height %s" % e) return if len(events): [print(json.dumps(e.ToJson(), indent=4)) for e in events] else: print("No events found for %s" % item) def show_wallet(self, arguments): if not self.Wallet: print("Please open a wallet") return item = get_arg(arguments) if not item: print("Wallet %s " % json.dumps(self.Wallet.ToJson(), indent=4)) return if item in ['v', '--v', 'verbose']: print("Wallet %s " % json.dumps(self.Wallet.ToJson(verbose=True), indent=4)) return elif item == 'migrate' and self.Wallet is not None: self.Wallet.Migrate() print("Migrated wallet") elif item == 'delete_addr': addr_to_delete = get_arg(arguments, 1) DeleteAddress(self, self.Wallet, addr_to_delete) elif item == 'delete_token': token_to_delete = get_arg(arguments, 1) DeleteToken(self.Wallet, token_to_delete) elif item == 'close': self.do_close_wallet() elif item == 'claim': ClaimGas(self.Wallet, True, arguments[1:]) elif item == 'rebuild': self.Wallet.Rebuild() try: item2 = int(get_arg(arguments, 1)) if item2 and item2 > 0: print("Restarting at %s" % item2) self.Wallet._current_height = item2 except Exception as e: pass elif item == 'tkn_send': token_send(self.Wallet, arguments[1:]) elif item == 'tkn_send_from': token_send_from(self.Wallet, arguments[1:]) elif item == 'tkn_send_blog': token_send_blog(self.Wallet, arguments[1:]) elif item == 'tkn_approve': token_approve_allowance(self.Wallet, arguments[1:]) elif item == 'tkn_allowance': token_get_allowance(self.Wallet, arguments[1:], verbose=True) elif item == 'tkn_mint': token_mint(self.Wallet, arguments[1:]) elif item == 'tkn_register': token_crowdsale_register(self.Wallet, arguments[1:]) elif item == 'unspent': ShowUnspentCoins(self.Wallet, arguments[1:]) elif item == 'alias': if len(arguments) == 3: AddAlias(self.Wallet, arguments[1], arguments[2]) else: print("Please supply an address and title") else: print("Wallet: '{}' is an invalid parameter".format(item)) def do_send(self, arguments): construct_and_send(self, self.Wallet, arguments) def do_sign(self, arguments): jsn = get_arg(arguments) parse_and_sign(self, self.Wallet, jsn) def show_state(self): height = Blockchain.Default().Height headers = Blockchain.Default().HeaderHeight diff = height - self.start_height now = datetime.datetime.utcnow() difftime = now - self.start_dt mins = difftime / datetime.timedelta(minutes=1) bpm = 0 if diff > 0 and mins > 0: bpm = diff / mins out = "Progress: %s / %s\n" % (height, headers) out += "Block-cache length %s\n" % Blockchain.Default().BlockCacheCount out += "Blocks since program start %s\n" % diff out += "Time elapsed %s mins\n" % mins out += "Blocks per min %s \n" % bpm tokens = [(Token.Number, out)] print_tokens(tokens, self.token_style) def show_nodes(self): if len(NodeLeader.Instance().Peers) > 0: out = "" for peer in NodeLeader.Instance().Peers: out += "Peer %s - IO: %s\n" % (peer.Name(), peer.IOStats()) print_tokens([(Token.Number, out)], self.token_style) else: print("Not connected yet\n") def show_block(self, args): item = get_arg(args) txarg = get_arg(args, 1) if item is not None: block = Blockchain.Default().GetBlock(item) if block is not None: bjson = json.dumps(block.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') if txarg and 'tx' in txarg: for tx in block.FullTransactions: print(json.dumps(tx.ToJson(), indent=4)) else: print("Could not locate block %s" % item) else: print("please specify a block") def show_header(self, args): item = get_arg(args) if item is not None: header = Blockchain.Default().GetHeaderBy(item) if header is not None: print(json.dumps(header.ToJson(), indent=4)) else: print("Could not locate header %s\n" % item) else: print("Please specify a header") def show_tx(self, args): if len(args): try: txid = UInt256.ParseString(get_arg(args)) tx, height = Blockchain.Default().GetTransaction(txid) if height > -1: jsn = tx.ToJson() jsn['height'] = height jsn['unspents'] = [ uns.ToJson(tx.outputs.index(uns)) for uns in Blockchain.Default().GetAllUnspent(txid) ] tokens = [(Token.Command, json.dumps(jsn, indent=4))] print_tokens(tokens, self.token_style) print('\n') except Exception as e: print("Could not find transaction from args: %s (%s)" % (e, args)) else: print("Please specify a TX hash") def show_account_state(self, args): item = get_arg(args) if item is not None: account = Blockchain.Default().GetAccountState( item, print_all_accounts=True) if account is not None: bjson = json.dumps(account.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Account %s not found" % item) else: print("Please specify an account address") def show_asset_state(self, args): item = get_arg(args) if item is not None: if item == 'search': query = get_arg(args, 1) results = Blockchain.Default().SearchAssetState(query) print("Found %s results for %s" % (len(results), query)) for asset in results: bjson = json.dumps(asset.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') return asset = Blockchain.Default().GetAssetState(item) if asset is not None: bjson = json.dumps(asset.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Asset %s not found" % item) else: print("Please specify an asset hash") def show_contract_state(self, args): item = get_arg(args) if item is not None: if item.lower() == 'all': contracts = Blockchain.Default().ShowAllContracts() print("Contracts: %s" % contracts) elif item.lower() == 'search': query = get_arg(args, 1) if query: contracts = Blockchain.Default().SearchContracts( query=query) print("Found %s results for %s" % (len(contracts), query)) for contract in contracts: bjson = json.dumps(contract.ToJson(), indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Please specify a search query") else: contract = Blockchain.Default().GetContract(item) if contract is not None: contract.DetermineIsNEP5() jsn = contract.ToJson() bjson = json.dumps(jsn, indent=4) tokens = [(Token.Number, bjson)] print_tokens(tokens, self.token_style) print('\n') else: print("Please specify a contract") def test_invoke_contract(self, args): if not self.Wallet: print("Please open a wallet") return if args and len(args) > 0: tx, fee, results, num_ops = TestInvokeContract(self.Wallet, args) if tx is not None and results is not None: print( "\n-------------------------------------------------------------------------------------------------------------------------------------" ) print("Test invoke successful") print("Total operations: %s" % num_ops) print("Results %s" % [str(item) for item in results]) print("Invoke TX GAS cost: %s" % (tx.Gas.value / Fixed8.D)) print("Invoke TX fee: %s" % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n" ) print( "Enter your password to continue and invoke on the network\n" ) passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, fee) return else: print("Error testing contract invoke") return print("Please specify a contract to invoke") def load_smart_contract(self, args): if not self.Wallet: print("Please open a wallet") return function_code = LoadContract(args[1:]) if function_code: contract_script = GatherContractDetails(function_code, self) if contract_script is not None: tx, fee, results, num_ops = test_invoke( contract_script, self.Wallet, []) if tx is not None and results is not None: print( "\n-------------------------------------------------------------------------------------------------------------------------------------" ) print("Test deploy invoke successful") print("Total operations executed: %s " % num_ops) print("Results:") print([item.GetInterface() for item in results]) print("Deploy Invoke TX GAS cost: %s " % (tx.Gas.value / Fixed8.D)) print("Deploy Invoke TX Fee: %s " % (fee.value / Fixed8.D)) print( "-------------------------------------------------------------------------------------------------------------------------------------\n" ) print( "Enter your password to continue and deploy this contract" ) passwd = prompt("[password]> ", is_password=True) if not self.Wallet.ValidatePassword(passwd): return print("Incorrect password") result = InvokeContract(self.Wallet, tx, Fixed8.Zero()) return else: print("Test invoke failed") print("TX is %s, results are %s" % (tx, results)) return def show_mem(self): process = psutil.Process(os.getpid()) total = process.memory_info().rss totalmb = total / (1024 * 1024) out = "Total: %s MB\n" % totalmb out += "Total buffers: %s\n" % StreamManager.TotalBuffers() print_tokens([(Token.Number, out)], self.token_style) def handle_debug_storage(self, args): what = get_arg(args) if what == 'on': settings.USE_DEBUG_STORAGE = True print("Debug storage on") elif what == 'off': settings.USE_DEBUG_STORAGE = False print("Debug Storage off") elif what == 'reset': DebugStorage.instance().reset() print("Reset debug storage") else: print("Please specify on|off|reset") def configure(self, args): what = get_arg(args) if what == 'debug': c1 = get_arg(args, 1).lower() if c1 is not None: if c1 == 'on' or c1 == '1': print("Debug logging is now enabled") settings.set_loglevel(logging.DEBUG) if c1 == 'off' or c1 == '0': print("Debug logging is now disabled") settings.set_loglevel(logging.INFO) else: print("Cannot configure log. Please specify on|off") elif what == 'sc-events': c1 = get_arg(args, 1).lower() if c1 is not None: if c1 == 'on' or c1 == '1': print("Smart contract event logging is now enabled") settings.set_log_smart_contract_events(True) if c1 == 'off' or c1 == '0': print("Smart contract event logging is now disabled") settings.set_log_smart_contract_events(False) else: print("Cannot configure log. Please specify on|off") else: print( "Cannot configure %s try 'config sc-events on|off' or 'config debug on|off'", what) def run(self): dbloop = task.LoopingCall(Blockchain.Default().PersistBlocks) dbloop.start(.1) Blockchain.Default().PersistBlocks() tokens = [(Token.Neo, 'NEO'), (Token.Default, ' cli. Type '), (Token.Command, '\'help\' '), (Token.Default, 'to get started')] print_tokens(tokens, self.token_style) print('\n') while self.go_on: try: result = prompt( "neo> ", completer=self.get_completer(), history=self.history, get_bottom_toolbar_tokens=self.get_bottom_toolbar, style=self.token_style, refresh_interval=3) except EOFError: # Control-D pressed: quit return self.quit() except KeyboardInterrupt: # Control-C pressed: do nothing continue try: command, arguments = self.input_parser.parse_input(result) if command is not None and len(command) > 0: command = command.lower() if command == 'quit' or command == 'exit': self.quit() elif command == 'help': self.help() elif command == 'create': self.do_create(arguments) elif command == 'open': self.do_open(arguments) elif command == 'build': self.do_build(arguments) elif command == 'load_run': self.do_load_n_run(arguments) elif command == 'import': self.do_import(arguments) elif command == 'export': self.do_export(arguments) elif command == 'wallet': self.show_wallet(arguments) elif command == 'send': self.do_send(arguments) elif command == 'sign': self.do_sign(arguments) elif command == 'block': self.show_block(arguments) elif command == 'tx': self.show_tx(arguments) elif command == 'header': self.show_header(arguments) elif command == 'account': self.show_account_state(arguments) elif command == 'asset': self.show_asset_state(arguments) elif command == 'contract': self.show_contract_state(arguments) elif command == 'testinvoke': self.test_invoke_contract(arguments) elif command == 'withdraw_request': self.make_withdraw_request(arguments) elif command == 'withdraw': self.do_withdraw(arguments) elif command == 'notifications': self.do_notifications(arguments) elif command == 'mem': self.show_mem() elif command == 'nodes' or command == 'node': self.show_nodes() elif command == 'state': self.show_state() elif command == 'debugstorage': self.handle_debug_storage(arguments) elif command == 'config': self.configure(arguments) elif command is None: print("Please specify a command") else: print("Command %s not found" % command) except Exception as e: print("Could not execute command: %s" % e) traceback.print_stack() traceback.print_exc()
def run_cli(self): iterations = 0 sqlexecute = self.sqlexecute logger = self.logger self.configure_pager() self.refresh_completions() history_file = config_location() + "history" if dir_path_exists(history_file): history = FileHistory(history_file) else: history = None self.echo( 'Error: Unable to open the history file "{}". ' "Your query history will not be saved.".format(history_file), err=True, fg="red", ) key_bindings = cli_bindings(self) if not self.less_chatty: print("Version:", __version__) print( "Mail: https://groups.google.com/forum/#!forum/litecli-users") print("Github: https://github.com/dbcli/litecli") # print("Home: https://litecli.com") def get_message(): prompt = self.get_prompt(self.prompt_format) if (self.prompt_format == self.default_prompt and len(prompt) > self.max_len_prompt): prompt = self.get_prompt("\\d> ") return [("class:prompt", prompt)] def get_continuation(width, line_number, is_soft_wrap): continuation = " " * (width - 1) + " " return [("class:continuation", continuation)] def show_suggestion_tip(): return iterations < 2 def one_iteration(text=None): if text is None: try: text = self.prompt_app.prompt() except KeyboardInterrupt: return special.set_expanded_output(False) try: text = self.handle_editor_command(text) except RuntimeError as e: logger.error("sql: %r, error: %r", text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") return if not text.strip(): return if self.destructive_warning: destroy = confirm_destructive_query(text) if destroy is None: pass # Query was not destructive. Nothing to do here. elif destroy is True: self.echo("Your call!") else: self.echo("Wise choice!") return # Keep track of whether or not the query is mutating. In case # of a multi-statement query, the overall query is considered # mutating if any one of the component statements is mutating mutating = False try: logger.debug("sql: %r", text) special.write_tee(self.get_prompt(self.prompt_format) + text) if self.logfile: self.logfile.write("\n# %s\n" % datetime.now()) self.logfile.write(text) self.logfile.write("\n") successful = False start = time() res = sqlexecute.run(text) self.formatter.query = text successful = True result_count = 0 for title, cur, headers, status in res: logger.debug("headers: %r", headers) logger.debug("rows: %r", cur) logger.debug("status: %r", status) threshold = 1000 if is_select(status) and cur and cur.rowcount > threshold: self.echo( "The result set has more than {} rows.".format( threshold), fg="red", ) if not confirm("Do you want to continue?"): self.echo("Aborted!", err=True, fg="red") break if self.auto_vertical_output: max_width = self.prompt_app.output.get_size().columns else: max_width = None formatted = self.format_output( title, cur, headers, special.is_expanded_output(), max_width) t = time() - start try: if result_count > 0: self.echo("") try: self.output(formatted, status) except KeyboardInterrupt: pass self.echo("Time: %0.03fs" % t) except KeyboardInterrupt: pass start = time() result_count += 1 mutating = mutating or is_mutating(status) special.unset_once_if_written() except EOFError as e: raise e except KeyboardInterrupt: # get last connection id connection_id_to_kill = sqlexecute.connection_id logger.debug("connection id to kill: %r", connection_id_to_kill) # Restart connection to the database sqlexecute.connect() try: for title, cur, headers, status in sqlexecute.run( "kill %s" % connection_id_to_kill): status_str = str(status).lower() if status_str.find("ok") > -1: logger.debug( "cancelled query, connection id: %r, sql: %r", connection_id_to_kill, text, ) self.echo("cancelled query", err=True, fg="red") except Exception as e: self.echo( "Encountered error while cancelling query: {}".format( e), err=True, fg="red", ) except NotImplementedError: self.echo("Not Yet Implemented.", fg="yellow") except OperationalError as e: logger.debug("Exception: %r", e) if e.args[0] in (2003, 2006, 2013): logger.debug("Attempting to reconnect.") self.echo("Reconnecting...", fg="yellow") try: sqlexecute.connect() logger.debug("Reconnected successfully.") one_iteration(text) return # OK to just return, cuz the recursion call runs to the end. except OperationalError as e: logger.debug("Reconnect failed. e: %r", e) self.echo(str(e), err=True, fg="red") # If reconnection failed, don't proceed further. return else: logger.error("sql: %r, error: %r", text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") except Exception as e: logger.error("sql: %r, error: %r", text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg="red") else: if is_dropping_database(text, self.sqlexecute.dbname): self.sqlexecute.dbname = None self.sqlexecute.connect() # Refresh the table names and column names if necessary. if need_completion_refresh(text): self.refresh_completions(reset=need_completion_reset(text)) finally: if self.logfile is False: self.echo("Warning: This query was not logged.", err=True, fg="red") query = Query(text, successful, mutating) self.query_history.append(query) get_toolbar_tokens = create_toolbar_tokens_func( self, show_suggestion_tip) if self.wider_completion_menu: complete_style = CompleteStyle.MULTI_COLUMN else: complete_style = CompleteStyle.COLUMN with self._completer_lock: if self.key_bindings == "vi": editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS self.prompt_app = PromptSession( lexer=PygmentsLexer(LiteCliLexer), reserve_space_for_menu=self.get_reserved_space(), message=get_message, prompt_continuation=get_continuation, bottom_toolbar=get_toolbar_tokens, complete_style=complete_style, input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(), ) ], tempfile_suffix=".sql", completer=DynamicCompleter(lambda: self.completer), history=history, auto_suggest=AutoSuggestFromHistory(), complete_while_typing=True, multiline=cli_is_multiline(self), style=style_factory(self.syntax_style, self.cli_style), include_default_pygments_style=False, key_bindings=key_bindings, enable_open_in_editor=True, enable_system_prompt=True, enable_suspend=True, editing_mode=editing_mode, search_ignore_case=True, ) try: while True: one_iteration() iterations += 1 except EOFError: special.close_tee() if not self.less_chatty: self.echo("Goodbye!")
def _create_application(self): """ Create CommandLineInterface instance. """ # Create Vi command buffer. def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. self.leave_command_mode(append_to_history=True) # Execute command. handle_command(self, text) # Create history and search buffers. commands_history = FileHistory( os.path.join(self.config_directory, 'commands_history')) command_buffer = Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=Always(), completer=create_command_completer(self), history=commands_history) search_buffer_history = FileHistory( os.path.join(self.config_directory, 'search_history')) search_buffer = Buffer(history=search_buffer_history, enable_history_search=Always(), accept_action=AcceptAction.IGNORE) # Create app. # Create CLI. application = Application( layout=self.editor_layout.layout, key_bindings_registry=self.key_bindings_manager.registry, buffers={ COMMAND_BUFFER: command_buffer, SEARCH_BUFFER: search_buffer, }, style=DynamicStyle(lambda: PygmentsStyle(self.current_style)), paste_mode=Condition(lambda cli: self.paste_mode), ignore_case=Condition(lambda cli: self.ignore_case), mouse_support=Condition(lambda cli: self.enable_mouse_support), use_alternate_screen=True, on_abort=AbortAction.IGNORE, on_exit=AbortAction.IGNORE, on_buffer_changed=Callback(self._current_buffer_changed)) # Handle command line previews. # (e.g. when typing ':colorscheme blue', it should already show the # preview before pressing enter.) def preview(): if self.cli.current_buffer == command_buffer: self.previewer.preview(command_buffer.text) command_buffer.on_text_changed += preview return application
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter print("""-----欢迎使用极云监控系统----- 常用命令: cpu、disk、memory、ip 使用exit命令退出系统!""") Completer = WordCompleter( ['cpu', 'disk', 'scan', 'ip', 'memory', 'times', 'exit', 'install', 'run'], ignore_case=True) while (1): try: getinput = prompt( 'GeekCloud:>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=Completer, ) if (str(getinput) == "exit" or str(getinput) == '^C'): print("退出系统!") break if (str(getinput) == ''): continue command = getattr(libs, getinput) command() except KeyboardInterrupt: print("退出系统!") break except: print('"' + str(getinput) + '"' + "不存在的命令!")
async def start(self): # default history file histfile = FileHistory('.shad0w_history') # do what prompts do self.set_autocompletes() try: with patch_stdout(): self.prompt_session = PromptSession( bottom_toolbar=self.beacon_toolbar, history=histfile, lexer=PygmentsLexer(cmd.Shad0wLexer), style=cmd.Shad0wLexer.lex_style, auto_suggest=AutoSuggestFromHistory()) except ValueError: pass while True: try: # display a prompt depending on wheather we got an active beacon or not if self.shad0w.current_beacon is None: input = await self.prompt_session.prompt_async( ANSI(self.prompt), completer=self.autocomplete, complete_style=CompleteStyle.READLINE_LIKE) else: # stuff to format for name domain = self.shad0w.beacons[ self.shad0w.current_beacon]["domain"] username = self.shad0w.beacons[ self.shad0w.current_beacon]["username"] machine = self.shad0w.beacons[ self.shad0w.current_beacon]["machine"] if domain != "NULL": with patch_stdout(): input = await self.prompt_session.prompt_async( ANSI(self.active_domain_prompt % (username, domain, machine)), completer=self.autocomplete, complete_style=CompleteStyle.READLINE_LIKE, refresh_interval=0.5) else: with patch_stdout(): input = await self.prompt_session.prompt_async( ANSI(self.active_prompt % (username, machine)), completer=self.autocomplete, complete_style=CompleteStyle.READLINE_LIKE, refresh_interval=0.5) # handle the input we just recived try: with patch_stdout(): await self.cmd_handler.do(input) except Exception as e: # tell user about error print("ERROR:", e) # if in debug mode drop the full traceback if self.shad0w.debugv: traceback.print_exc() pass except KeyboardInterrupt: break # exit, trying to make it nicely self.shad0w.debug.log(f"Shad0w exiting...", log=True) exit()
db = Database(dbname, load=True) if fname is not None: for line in open(fname, 'r').read().splitlines(): if line.startswith('--'): continue dic = interpret(line.lower()) result = execute_dic(dic) if isinstance(result,Table): result.show() else: from prompt_toolkit import PromptSession from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory print(art) session = PromptSession(history=FileHistory('.inp_history')) while 1: try: line = session.prompt(f'({db._name})> ', auto_suggest=AutoSuggestFromHistory()).lower() if line[-1]!=';': line+=';' except (KeyboardInterrupt, EOFError): print('\nbye!') break try: if line=='exit': break if line.startswith('.'): interpret_meta(line) elif line.startswith('explain'): dic = interpret(line.removeprefix('explain '))
def cli(spec, env, url, http_options): click.echo('Version: %s' % __version__) copied, config_path = config.initialize() if copied: click.echo('Config file not found. Initialized a new one: %s' % config_path) cfg = config.load() # Override pager/less options os.environ['PAGER'] = cfg['pager'] os.environ['LESS'] = '-RXF' if spec: f = urlopen(spec) try: content = f.read().decode('utf-8') try: spec = json.loads(content) except json.JSONDecodeError: try: spec = yaml.load(content) except yaml.YAMLError: click.secho("Warning: Specification file '%s' is neither valid JSON nor YAML" % spec, err=True, fg='red') spec = None finally: f.close() if url: url = fix_incomplete_url(url) context = Context(url, spec=spec) output_style = cfg.get('output_style') if output_style: context.options['--style'] = output_style # For prompt-toolkit history = FileHistory(os.path.join(get_data_dir(), 'history')) lexer = PygmentsLexer(HttpPromptLexer) completer = HttpPromptCompleter(context) try: style_class = get_style_by_name(cfg['command_style']) except ClassNotFound: style_class = Solarized256Style style = style_from_pygments(style_class) listener = ExecutionListener(cfg) if len(sys.argv) == 1: # load previous context if nothing defined load_context(context) else: if env: load_context(context, env) if url: # Overwrite the env url if not default context.url = url if http_options: # Execute HTTPie options from CLI (can overwrite env file values) http_options = [smart_quote(a) for a in http_options] execute(' '.join(http_options), context, listener=listener) while True: try: text = prompt('%s> ' % context.url, completer=completer, lexer=lexer, style=style, history=history, auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, vi_mode=cfg['vi']) except EOFError: break # Control-D pressed else: execute(text, context, listener=listener, style=style_class) if context.should_exit: break click.echo("Goodbye!")
def cli_search(args): """Command-line interface for search call.""" bibs = bm.load() completer = u.KeyWordCompleter(u.search_keywords, bibs) suggester = u.AutoSuggestKeyCompleter() validator = u.AlwaysPassValidator(bibs, "(Press 'tab' for autocomplete)") session = prompt_toolkit.PromptSession( history=FileHistory(u.BM_HISTORY_SEARCH())) inputs = session.prompt( "(Press 'tab' for autocomplete)\n", auto_suggest=suggester, completer=completer, complete_while_typing=False, validator=validator, validate_while_typing=True, bottom_toolbar=validator.bottom_toolbar) # Parse inputs: authors = re.findall(r'author:"([^"]+)', inputs) title_kw = re.findall(r'title:"([^"]+)', inputs) years = re.search(r'year:[\s]*([^\s]+)', inputs) key = re.findall(r'key:[\s]*([^\s]+)', inputs) bibcode = re.findall(r'bibcode:[\s]*([^\s]+)', inputs) if years is not None: years = years.group(1) if len(key) == 0: key = None if len(bibcode) == 0: bibcode = None # Cast year string to integer or list of integers: if years is None: pass elif len(years) == 4 and years.isnumeric(): years = int(years) elif len(years) == 5 and years.startswith('-') and years[1:].isnumeric(): years = [0, int(years[1:])] elif len(years) == 5 and years.endswith('-') and years[0:4].isnumeric(): years = [int(years[0:4]), 9999] elif len(years) == 9 and years[0:4].isnumeric() and years[5:].isnumeric(): years = [int(years[0:4]), int(years[5:9])] else: print(f"\nInvalid format for input year: {years}") return if (len(authors) == 0 and len(title_kw) == 0 and years is None and key is None and bibcode is None): return matches = bm.search(authors, years, title_kw, key, bibcode) # Display outputs depending on the verb level: if args.verb >= 3: bm.display_bibs(labels=None, bibs=matches, meta=True) return for match in matches: title = textwrap.fill(f"Title: {match.title}, {match.year}", width=78, subsequent_indent=' ') author_format = 'short' if args.verb < 2 else 'long' authors = textwrap.fill( f"Authors: {match.get_authors(format=author_format)}", width=78, subsequent_indent=' ') keys = f"\nkey: {match.key}" if args.verb > 0 and match.pdf is not None: keys = f"\nPDF file: {match.pdf}{keys}" if args.verb > 0 and match.eprint is not None: keys = f"\narXiv url: http://arxiv.org/abs/{match.eprint}{keys}" if args.verb > 0 and match.adsurl is not None: keys = f"\nADS url: {match.adsurl}{keys}" keys = f"\nbibcode: {match.bibcode}{keys}" print(f"\n{title}\n{authors}{keys}")
#!/usr/bin/env python from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory while True: user_input = prompt(u'>', history=FileHistory('history.txt')) print user_input
def run_cli(self): iterations = 0 sqlexecute = self.sqlexecute logger = self.logger self.configure_pager() if self.smart_completion: self.refresh_completions() author_file = os.path.join(PACKAGE_ROOT, 'AUTHORS') sponsor_file = os.path.join(PACKAGE_ROOT, 'SPONSORS') history_file = os.path.expanduser( os.environ.get('MYCLI_HISTFILE', '~/.mycli-history')) if dir_path_exists(history_file): history = FileHistory(history_file) else: history = None self.echo( 'Error: Unable to open the history file "{}". ' 'Your query history will not be saved.'.format(history_file), err=True, fg='red') key_binding_manager = mycli_bindings() if not self.less_chatty: print('Version:', __version__) print('Chat: https://gitter.im/dbcli/mycli') print('Mail: https://groups.google.com/forum/#!forum/mycli-users') print('Home: http://mycli.net') print('Thanks to the contributor -', thanks_picker([author_file, sponsor_file])) def prompt_tokens(cli): prompt = self.get_prompt(self.prompt_format) if self.prompt_format == self.default_prompt and len(prompt) > self.max_len_prompt: prompt = self.get_prompt('\\d> ') return [(Token.Prompt, prompt)] def get_continuation_tokens(cli, width): continuation_prompt = self.get_prompt(self.prompt_continuation_format) return [(Token.Continuation, ' ' * (width - len(continuation_prompt)) + continuation_prompt)] def show_suggestion_tip(): return iterations < 2 def one_iteration(document=None): if document is None: document = self.cli.run() special.set_expanded_output(False) try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg='red') return if not document.text.strip(): return if self.destructive_warning: destroy = confirm_destructive_query(document.text) if destroy is None: pass # Query was not destructive. Nothing to do here. elif destroy is True: self.echo('Your call!') else: self.echo('Wise choice!') return # Keep track of whether or not the query is mutating. In case # of a multi-statement query, the overall query is considered # mutating if any one of the component statements is mutating mutating = False try: logger.debug('sql: %r', document.text) special.write_tee(self.get_prompt(self.prompt_format) + document.text) if self.logfile: self.logfile.write('\n# %s\n' % datetime.now()) self.logfile.write(document.text) self.logfile.write('\n') successful = False start = time() res = sqlexecute.run(document.text) self.formatter.query = document.text successful = True result_count = 0 for title, cur, headers, status in res: logger.debug("headers: %r", headers) logger.debug("rows: %r", cur) logger.debug("status: %r", status) threshold = 1000 if (is_select(status) and cur and cur.rowcount > threshold): self.echo('The result set has more than {} rows.'.format( threshold), fg='red') if not confirm('Do you want to continue?'): self.echo("Aborted!", err=True, fg='red') break if self.auto_vertical_output: max_width = self.cli.output.get_size().columns else: max_width = None formatted = self.format_output( title, cur, headers, special.is_expanded_output(), max_width) t = time() - start try: if result_count > 0: self.echo('') try: self.output(formatted, status) except KeyboardInterrupt: pass if special.is_timing_enabled(): self.echo('Time: %0.03fs' % t) except KeyboardInterrupt: pass start = time() result_count += 1 mutating = mutating or is_mutating(status) special.unset_once_if_written() except EOFError as e: raise e except KeyboardInterrupt: # get last connection id connection_id_to_kill = sqlexecute.connection_id logger.debug("connection id to kill: %r", connection_id_to_kill) # Restart connection to the database sqlexecute.connect() try: for title, cur, headers, status in sqlexecute.run('kill %s' % connection_id_to_kill): status_str = str(status).lower() if status_str.find('ok') > -1: logger.debug("cancelled query, connection id: %r, sql: %r", connection_id_to_kill, document.text) self.echo("cancelled query", err=True, fg='red') except Exception as e: self.echo('Encountered error while cancelling query: {}'.format(e), err=True, fg='red') except NotImplementedError: self.echo('Not Yet Implemented.', fg="yellow") except OperationalError as e: logger.debug("Exception: %r", e) if (e.args[0] in (2003, 2006, 2013)): logger.debug('Attempting to reconnect.') self.echo('Reconnecting...', fg='yellow') try: sqlexecute.connect() logger.debug('Reconnected successfully.') one_iteration(document) return # OK to just return, cuz the recursion call runs to the end. except OperationalError as e: logger.debug('Reconnect failed. e: %r', e) self.echo(str(e), err=True, fg='red') # If reconnection failed, don't proceed further. return else: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg='red') except Exception as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.echo(str(e), err=True, fg='red') else: if is_dropping_database(document.text, self.sqlexecute.dbname): self.sqlexecute.dbname = None self.sqlexecute.connect() # Refresh the table names and column names if necessary. if need_completion_refresh(document.text): self.refresh_completions( reset=need_completion_reset(document.text)) finally: if self.logfile is False: self.echo("Warning: This query was not logged.", err=True, fg='red') query = Query(document.text, successful, mutating) self.query_history.append(query) get_toolbar_tokens = create_toolbar_tokens_func( self.completion_refresher.is_refreshing, show_suggestion_tip) layout = create_prompt_layout( lexer=MyCliLexer, multiline=True, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, extra_input_processors=[ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() )], reserve_space_for_menu=self.get_reserved_space() ) with self._completer_lock: buf = CLIBuffer( always_multiline=self.multi_line, completer=self.completer, history=history, auto_suggest=AutoSuggestFromHistory(), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) if self.key_bindings == 'vi': editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS application = Application( style=style_from_pygments(style_cls=self.output_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, editing_mode=editing_mode, ignore_case=True) self.cli = CommandLineInterface(application=application, eventloop=create_eventloop()) try: while True: one_iteration() iterations += 1 except EOFError: special.close_tee() if not self.less_chatty: self.echo('Goodbye!')
def __init__(self, completekey='tab', stdin=None, stdout=None): BaseCmd.__init__(self, completekey, stdin, stdout) self.history = FileHistory(os.path.expanduser(HISTORY_PATH))
def __call__(self): def get_prompt_tokens(cli): return [ (Token.Username, ContrailAPISession.user or ''), (Token.At, '@' if ContrailAPISession.user else ''), (Token.Host, ContrailAPISession.host), (Token.Colon, ':'), (Token.Path, text_type(Context().shell.current_path)), (Token.Pound, '> ') ] key_bindings_registry = KeyBindingManager.for_prompt().registry manager = CommandManager() manager.load_namespace('contrail_api_cli.shell_command') completer = ShellCompleter() history = FileHistory(os.path.join(CONFIG_DIR, 'history')) cmd_aliases = ShellAliases() for cmd_name, cmd in manager.list: map(cmd_aliases.set, cmd.aliases) # load home resources to have them in cache # also build shortcut list for resource types # typing vmi/ will be expanded to virtual-machine-interface/ # automagically res_aliases = ShellAliases() try: for c in RootCollection(fetch=True): short_name = "".join([p if p == "ip" else p[0].lower() for p in c.type.split('-')]) res_aliases.set("%s = %s" % (short_name, c.type)) except ClientException as e: return text_type(e) def _(event, aliases, char): b = event.cli.current_buffer w = b.document.get_word_before_cursor() if w is not None: if not w == aliases.get(w): b.delete_before_cursor(count=len(w)) b.insert_text(aliases.get(w)) b.insert_text(char) @key_bindings_registry.add_binding(' ') def _sa(event): _(event, cmd_aliases, ' ') @key_bindings_registry.add_binding('/') def _ra(event): _(event, res_aliases, '/') while True: try: action = prompt(get_prompt_tokens=get_prompt_tokens, history=history, completer=completer, style=default_style, eventloop=eventloop(), key_bindings_registry=key_bindings_registry) action = cmd_aliases.apply(action) except (EOFError, KeyboardInterrupt): break try: action = action.split('|') pipe_cmds = action[1:] action = shlex.split(action[0]) cmd = manager.get(action[0]) args = action[1:] if pipe_cmds: p = pipes.Template() for pipe_cmd in pipe_cmds: p.append(str(pipe_cmd.strip()), '--') cmd.is_piped = True else: cmd.is_piped = False except IndexError: continue except CommandNotFound as e: printo(text_type(e)) continue try: result = cmd.parse_and_call(*args) except (HttpError, ClientException, CommandError, NotFound, Exists) as e: printo(text_type(e)) continue except KeyboardInterrupt: continue except EOFError: break else: if not result: continue elif pipe_cmds: t = tempfile.NamedTemporaryFile('r') with p.open(t.name, 'w') as f: f.write(result) printo(t.read().strip()) else: printo(result)
def run_cli(self): logger = self.logger history_file = self.config['main']['history_file'] if history_file == 'default': history_file = config_location() + 'history' history = FileHistory(os.path.expanduser(history_file)) self.refresh_completions(history=history, persist_priorities='none') self.cli = self._build_cli(history) if not self.less_chatty: print('Version:', __version__) print('Chat: https://gitter.im/dbcli/pgcli') print('Mail: https://groups.google.com/forum/#!forum/pgcli') print('Home: http://pgcli.com') try: while True: document = self.cli.run() # The reason we check here instead of inside the pgexecute is # because we want to raise the Exit exception which will be # caught by the try/except block that wraps the pgexecute.run() # statement. if quit_command(document.text): raise EOFError try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg='red') continue # Initialize default metaquery in case execution fails query = MetaQuery(query=document.text, successful=False) watch_command, timing = special.get_watch_command(document.text) if watch_command: while watch_command: try: query = self.execute_command(watch_command, query) click.echo('Waiting for {0} seconds before repeating'.format(timing)) sleep(timing) except KeyboardInterrupt: watch_command = None else: query = self.execute_command(document.text, query) self.now = dt.datetime.today() # Allow PGCompleter to learn user's preferred keywords, etc. with self._completer_lock: self.completer.extend_query_history(document.text) self.query_history.append(query) except EOFError: if not self.less_chatty: print ('Goodbye!')
def __init__( self, get_globals=None, get_locals=None, history_filename=None, vi_mode=False, input=None, output=None, color_depth=None, # For internal use. extra_key_bindings=None, _completer=None, _validator=None, _lexer=None, _extra_buffer_processors=None, _extra_layout_body=None, _extra_toolbars=None, _input_buffer_height=None): self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self._completer = _completer or PythonCompleter( self.get_globals, self.get_locals) self._validator = _validator or PythonValidator( self.get_compiler_flags) self._lexer = _lexer or PygmentsLexer(PythonLexer) if history_filename: self.history = ThreadedHistory(FileHistory(history_filename)) else: self.history = InMemoryHistory() self._input_buffer_height = _input_buffer_height self._extra_layout_body = _extra_layout_body or [] self._extra_toolbars = _extra_toolbars or [] self._extra_buffer_processors = _extra_buffer_processors or [] self.extra_key_bindings = extra_key_bindings or KeyBindings() # Settings. self.show_signature = False self.show_docstring = False self.show_meta_enter_message = True self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN self.completion_menu_scroll_offset = 1 self.show_line_numbers = False self.show_status_bar = True self.wrap_lines = True self.complete_while_typing = True self.paste_mode = False # When True, don't insert whitespace after newline. self.confirm_exit = True # Ask for confirmation when Control-D is pressed. self.accept_input_on_enter = 2 # Accept when pressing Enter 'n' times. # 'None' means that meta-enter is always required. self.enable_open_in_editor = True self.enable_system_bindings = True self.enable_input_validation = True self.enable_auto_suggest = False self.enable_mouse_support = False self.enable_history_search = False # When True, like readline, going # back in history will filter the # history on the records starting # with the current input. self.enable_syntax_highlighting = True self.swap_light_and_dark = False self.highlight_matching_parenthesis = False self.show_sidebar = False # Currently show the sidebar. self.show_sidebar_help = True # When the sidebar is visible, also show the help text. self.show_exit_confirmation = False # Currently show 'Do you really want to exit?' self.terminal_title = None # The title to be displayed in the terminal. (None or string.) self.exit_message = 'Do you really want to exit?' self.insert_blank_line_after_output = True # (For the REPL.) # The buffers. self.default_buffer = self._create_buffer() self.search_buffer = Buffer() self.docstring_buffer = Buffer(read_only=True) # Tokens to be shown at the prompt. self.prompt_style = 'classic' # The currently active style. self.all_prompt_styles = { # Styles selectable from the menu. 'ipython': IPythonPrompt(self), 'classic': ClassicPrompt(), } self.get_input_prompt = lambda: \ self.all_prompt_styles[self.prompt_style].in_prompt() self.get_output_prompt = lambda: \ self.all_prompt_styles[self.prompt_style].out_prompt() #: Load styles. self.code_styles = get_all_code_styles() self.ui_styles = get_all_ui_styles() self._current_code_style_name = 'default' self._current_ui_style_name = 'default' if is_windows(): self._current_code_style_name = 'win32' self._current_style = self._generate_style() self.color_depth = color_depth or ColorDepth.default() self.max_brightness = 1.0 self.min_brightness = 0.0 # Options to be configurable from the sidebar. self.options = self._create_options() self.selected_option_index = 0 #: Incremeting integer counting the current statement. self.current_statement_index = 1 # Code signatures. (This is set asynchronously after a timeout.) self.signatures = [] # Boolean indicating whether we have a signatures thread running. # (Never run more than one at the same time.) self._get_signatures_thread_running = False self.output = output or create_output() self.input = input or create_input(sys.stdin) self.style_transformation = merge_style_transformations([ ConditionalStyleTransformation( SwapLightAndDarkStyleTransformation(), filter=Condition(lambda: self.swap_light_and_dark)), AdjustBrightnessStyleTransformation(lambda: self.min_brightness, lambda: self.max_brightness), ]) self.ptpython_layout = PtPythonLayout( self, lexer=DynamicLexer(lambda: self._lexer if self. enable_syntax_highlighting else SimpleLexer()), input_buffer_height=self._input_buffer_height, extra_buffer_processors=self._extra_buffer_processors, extra_body=self._extra_layout_body, extra_toolbars=self._extra_toolbars) self.app = self._create_application() if vi_mode: self.app.editing_mode = EditingMode.VI
def main(): now = datetime.datetime.now() print('acticated ', now) while 1: try: user_input = prompt( 'DPDK FW>', history=FileHistory('data/history'), auto_suggest=AutoSuggestFromHistory(), complete_while_typing=True, completer=CommandCompleter, style=style, ) print('input:' + user_input) # print(type(user_input)) # print(user_input) # print(type(user_input)) user_input = user_input.split() command = None arg = None try: command = user_input[0] # print('command:' + command) except: pass try: arg = user_input[1] # print('arg:'+arg) except IndexError: pass if command == 'exit': break elif command == 'quit': break elif command == 'run': print('will run DPDK app') dpdk = subprocess.Popen('./a.out') pid = dpdk.pid elif command == 'stop': dpdk.terminate() print('terminate DPDK app') elif command == 'kill': dpdk.kill() print('kill DPDK app') elif command == 'show': if arg is None: print('usage:' + command) elif arg is not None: arg = 'data/' + arg try: f = open(arg, 'r') data = f.read() print('filename:' + arg) print('=====================') print(data, end='') print('=====================') f.close() except FileNotFoundError: print(arg + ':file or directory not found') elif command == 'edit': if arg is None: print('usage:' + command) elif arg is not None: f = 'data/' + arg print(f) click.edit(filename=f) # print(user_input) elif command == 'delete': print('not yet') elif command is None: pass else: print(command + ':command is not defined') except KeyboardInterrupt: continue except EOFError: break print('Good Bye')
def run_cli(self): logger = self.logger history_file = self.config['main']['history_file'] if history_file == 'default': history_file = config_location() + 'history' history = FileHistory(os.path.expanduser(history_file)) self.refresh_completions(history=history, persist_priorities='none') self.cli = self._build_cli(history) print('Version:', __version__) print('Chat: https://gitter.im/dbcli/pgcli') print('Mail: https://groups.google.com/forum/#!forum/pgcli') print('Home: http://pgcli.com') try: while True: document = self.cli.run(True) # The reason we check here instead of inside the pgexecute is # because we want to raise the Exit exception which will be # caught by the try/except block that wraps the pgexecute.run() # statement. if quit_command(document.text): raise EOFError try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg='red') continue # Initialize default metaquery in case execution fails query = MetaQuery(query=document.text, successful=False) try: output, query = self._evaluate_command(document.text) except KeyboardInterrupt: # Restart connection to the database self.pgexecute.connect() logger.debug("cancelled query, sql: %r", document.text) click.secho("cancelled query", err=True, fg='red') except NotImplementedError: click.secho('Not Yet Implemented.', fg="yellow") except OperationalError as e: if ('server closed the connection' in utf8tounicode(e.args[0])): self._handle_server_closed_connection() else: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg='red') except Exception as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg='red') else: try: if self.output_file and not document.text.startswith( ('\\o ', '\\? ')): try: with open(self.output_file, 'a', encoding='utf-8') as f: click.echo(document.text, file=f) click.echo('\n'.join(output), file=f) click.echo('', file=f) # extra newline except IOError as e: click.secho(str(e), err=True, fg='red') else: click.echo_via_pager('\n'.join(output)) except KeyboardInterrupt: pass if self.pgspecial.timing_enabled: # Only add humanized time display if > 1 second if query.total_time > 1: print( 'Time: %0.03fs (%s)' % (query.total_time, humanize.time.naturaldelta(query.total_time))) else: print('Time: %0.03fs' % query.total_time) # Check if we need to update completions, in order of most # to least drastic changes if query.db_changed: with self._completer_lock: self.completer.reset_completions() self.refresh_completions(persist_priorities='keywords') elif query.meta_changed: self.refresh_completions(persist_priorities='all') elif query.path_changed: logger.debug('Refreshing search path') with self._completer_lock: self.completer.set_search_path( self.pgexecute.search_path()) logger.debug('Search path: %r', self.completer.search_path) # Allow PGCompleter to learn user's preferred keywords, etc. with self._completer_lock: self.completer.extend_query_history(document.text) self.query_history.append(query) except EOFError: print('Goodbye!')
def run_cli(self): sqlexecute = self.sqlexecute logger = self.logger self.configure_pager() self.refresh_completions() project_root = os.path.dirname(PACKAGE_ROOT) author_file = os.path.join(project_root, 'AUTHORS') sponsor_file = os.path.join(project_root, 'SPONSORS') key_binding_manager = mycli_bindings() if not self.less_chatty: print('Version:', __version__) print('Chat: https://gitter.im/dbcli/mycli') print('Mail: https://groups.google.com/forum/#!forum/mycli-users') print('Home: http://mycli.net') print('Thanks to the contributor -', thanks_picker([author_file, sponsor_file])) def prompt_tokens(cli): return [(Token.Prompt, self.get_prompt(self.prompt_format))] def get_continuation_tokens(cli, width): continuation_prompt = self.get_prompt( self.prompt_continuation_format) return [(Token.Continuation, ' ' * (width - len(continuation_prompt)) + continuation_prompt)] def one_iteration(document=None): if document is None: document = self.cli.run(reset_current_buffer=True) special.set_expanded_output(False) # The reason we check here instead of inside the sqlexecute is # because we want to raise the Exit exception which will be # caught by the try/except block that wraps the # sqlexecute.run() statement. if quit_command(document.text): raise EOFError try: document = self.handle_editor_command(self.cli, document) except RuntimeError as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.output(str(e), err=True, fg='red') return if self.destructive_warning: destroy = confirm_destructive_query(document.text) if destroy is None: pass # Query was not destructive. Nothing to do here. elif destroy is True: self.output('Your call!') else: self.output('Wise choice!') return # Keep track of whether or not the query is mutating. In case # of a multi-statement query, the overall query is considered # mutating if any one of the component statements is mutating mutating = False try: logger.debug('sql: %r', document.text) if self.logfile: self.logfile.write('\n# %s\n' % datetime.now()) self.logfile.write(document.text) self.logfile.write('\n') successful = False start = time() res = sqlexecute.run(document.text) successful = True output = [] total = 0 for title, cur, headers, status in res: logger.debug("headers: %r", headers) logger.debug("rows: %r", cur) logger.debug("status: %r", status) threshold = 1000 if (is_select(status) and cur and cur.rowcount > threshold): self.output('The result set has more than %s rows.' % threshold, fg='red') if not click.confirm('Do you want to continue?'): self.output("Aborted!", err=True, fg='red') break if self.auto_vertical_output: max_width = self.cli.output.get_size().columns else: max_width = None formatted = format_output(title, cur, headers, status, self.table_format, special.is_expanded_output(), max_width) output.extend(formatted) end = time() total += end - start mutating = mutating or is_mutating(status) except UnicodeDecodeError as e: import pymysql if pymysql.VERSION < (0, 6, 7): message = ( 'You are running an older version of pymysql.\n' 'Please upgrade to 0.6.7 or above to view binary data.\n' 'Try \'pip install -U pymysql\'.') self.output(message) else: raise e except KeyboardInterrupt: # Restart connection to the database sqlexecute.connect() logger.debug("cancelled query, sql: %r", document.text) self.output("cancelled query", err=True, fg='red') except NotImplementedError: self.output('Not Yet Implemented.', fg="yellow") except OperationalError as e: logger.debug("Exception: %r", e) if (e.args[0] in (2003, 2006, 2013)): logger.debug('Attempting to reconnect.') self.output('Reconnecting...', fg='yellow') try: sqlexecute.connect() logger.debug('Reconnected successfully.') one_iteration(document) return # OK to just return, cuz the recursion call runs to the end. except OperationalError as e: logger.debug('Reconnect failed. e: %r', e) self.output(str(e), err=True, fg='red') return # If reconnection failed, don't proceed further. else: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.output(str(e), err=True, fg='red') except Exception as e: logger.error("sql: %r, error: %r", document.text, e) logger.error("traceback: %r", traceback.format_exc()) self.output(str(e), err=True, fg='red') else: try: if special.is_pager_enabled(): self.output_via_pager('\n'.join(output)) else: self.output('\n'.join(output)) except KeyboardInterrupt: pass if special.is_timing_enabled(): self.output('Time: %0.03fs' % total) # Refresh the table names and column names if necessary. if need_completion_refresh(document.text): self.refresh_completions( reset=need_completion_reset(document.text)) finally: if self.logfile is False: self.output("Warning: This query was not logged.", err=True, fg='red') query = Query(document.text, successful, mutating) self.query_history.append(query) get_toolbar_tokens = create_toolbar_tokens_func( self.completion_refresher.is_refreshing) layout = create_prompt_layout( lexer=MyCliLexer, multiline=True, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()), ]) with self._completer_lock: buf = CLIBuffer(always_multiline=self.multi_line, completer=self.completer, history=FileHistory( os.path.expanduser( os.environ.get('MYCLI_HISTFILE', '~/.mycli-history'))), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) if self.key_bindings == 'vi': editing_mode = EditingMode.VI else: editing_mode = EditingMode.EMACS application = Application( style=style_factory(self.syntax_style, self.cli_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, editing_mode=editing_mode, ignore_case=True) self.cli = CommandLineInterface(application=application, eventloop=create_eventloop()) try: while True: one_iteration() except EOFError: if not self.less_chatty: self.output('Goodbye!')