def write_console_ex(buf, otype): if otype == 0: if not SUPPRESS_STDOUT: buf = buf.replace("\r\n", "\n") sbuf = buf.split("\r") for i, b in enumerate(sbuf): print_formatted_text(ANSI(b), end="", output=output) if i < len(sbuf) - 1: output.write("\r") output.flush() TERMINAL_CURSOR_AT_BEGINNING[0] = buf.endswith("\n") else: if not SUPPRESS_STDERR: buf = buf.replace("\r\n", "\n") sbuf = buf.split("\r") for i, b in enumerate(sbuf): print_formatted_text(ANSI(stderr_format.format(b)), end="", output=output) if i < len(sbuf) - 1: output.write("\r") output.flush() TERMINAL_CURSOR_AT_BEGINNING[0] = buf.endswith("\n")
def update(self): if self.read_callback is not None: val = self.read_callback( ) if self.read_callback_params is None else self.read_callback( self.read_callback_params) if self.is_progress_bar: val = int(val) val_percent = (val / self.progress_bar_range) * 100 self.value_label._percentage = val_percent if val_percent <= 100.0 else 100.0 self.value_label.label.text = "%d" % val else: self.value_label.text = ANSI(val) elif self.value_format_str is None: val = rw.read_reg(self.regs[0], verbose=False) if self.is_progress_bar: val_percent = (val / self.progress_bar_range) * 100 self.value_label._percentage = val_percent if val_percent <= 100.0 else 100.0 self.value_label.label.text = "%d" % val else: self.value_label.text = ANSI(val.to_string()) else: vals = [] for reg in self.regs: vals.append(rw.read_reg(reg, verbose=False)) val_str = self.value_format_str % tuple(vals) self.value_label.text = ANSI(val_str)
def test_ansi_formatting(): value = ANSI('\x1b[32mHe\x1b[45mllo') assert to_formatted_text(value) == [ ('ansigreen', 'H'), ('ansigreen', 'e'), ('ansigreen bg:ansimagenta', 'l'), ('ansigreen bg:ansimagenta', 'l'), ('ansigreen bg:ansimagenta', 'o'), ] # Bold and italic. value = ANSI('\x1b[1mhe\x1b[0mllo') assert to_formatted_text(value) == [ ('bold', 'h'), ('bold', 'e'), ('', 'l'), ('', 'l'), ('', 'o'), ] # Zero width escapes. value = ANSI('ab\001cd\002ef') assert to_formatted_text(value) == [ ('', 'a'), ('', 'b'), ('[ZeroWidthEscape]', 'cd'), ('', 'e'), ('', 'f'), ] assert isinstance(to_formatted_text(value), FormattedText)
def test_ansi_formatting(): value = ANSI("\x1b[32mHe\x1b[45mllo") assert to_formatted_text(value) == [ ("ansigreen", "H"), ("ansigreen", "e"), ("ansigreen bg:ansimagenta", "l"), ("ansigreen bg:ansimagenta", "l"), ("ansigreen bg:ansimagenta", "o"), ] # Bold and italic. value = ANSI("\x1b[1mhe\x1b[0mllo") assert to_formatted_text(value) == [ ("bold", "h"), ("bold", "e"), ("", "l"), ("", "l"), ("", "o"), ] # Zero width escapes. value = ANSI("ab\001cd\002ef") assert to_formatted_text(value) == [ ("", "a"), ("", "b"), ("[ZeroWidthEscape]", "cd"), ("", "e"), ("", "f"), ] assert isinstance(to_formatted_text(value), FormattedText)
def run(self, key, value=None): if key == "modules": h = Module.get_help(value) if h.strip() != "": print_formatted_text(h) else: self.logger.warning("No module loaded") elif key == "options": if value is None: print_formatted_text(ANSI(str(self.config))) else: c = Config() c[self.config.option(value)] = self.config[value] print_formatted_text(ANSI(str(c))) elif key == "projects": if value is None: data = [["Name"]] for p in projects(self): data.append([p]) print_formatted_text(BorderlessTable(data, "Existing projects")) else: print_formatted_text(value) elif key == "issues": t = Entity.get_issues() if len(t) > 0: print_formatted_text(t)
def app_initialize(self, mp): if sys.platform.startswith('win'): encoding = api.encoding() callbacks.ENCODING = encoding if not interface.get_option("rtichoke.suppress_reticulate_message", False): interface.reticulate_set_message(RETICULATE_MESSAGE) if interface.get_option("rtichoke.editing_mode", "emacs") in ["vim", "vi"]: mp.app.editing_mode = EditingMode.VI else: mp.app.editing_mode = EditingMode.EMACS color_scheme = interface.get_option("rtichoke.color_scheme", "native") mp.style = style_from_pygments_cls(get_style_by_name(color_scheme)) mp.app.auto_match = interface.get_option("rtichoke.auto_match", False) mp.app.auto_indentation = interface.get_option("rtichoke.auto_indentation", True) mp.app.tab_size = int(interface.get_option("rtichoke.tab_size", 4)) mp.complete_while_typing = interface.get_option("rtichoke.complete_while_typing", True) mp.history_search_no_duplicates = interface.get_option("rtichoke.history_search_no_duplicates", False) mp.insert_new_line = interface.get_option("rtichoke.insert_new_line", True) prompt = interface.get_option("rtichoke.prompt", None) if prompt: mp.set_prompt_mode_message("r", ANSI(prompt)) else: sys_prompt = interface.get_option("prompt") if sys_prompt == "> ": prompt = PROMPT else: prompt = sys_prompt mp.default_prompt = prompt mp.set_prompt_mode_message("r", ANSI(prompt)) interface.set_option("prompt", prompt) shell_prompt = interface.get_option("rtichoke.shell_prompt", SHELL_PROMPT) mp.set_prompt_mode_message("shell", ANSI(shell_prompt)) mp.browse_prompt = interface.get_option("rtichoke.browse_prompt", BROWSE_PROMPT) set_width_on_resize = interface.get_option("setWidthOnResize", True) mp.auto_width = interface.get_option("rtichoke.auto_width", set_width_on_resize) if mp.auto_width: interface.set_option("width", mp.app.output.get_size().columns) # necessary on windows interface.set_option("menu.graphics", False) # enables completion of installed package names if interface.rcopy(interface.reval("rc.settings('ipck')")) is None: interface.reval("rc.settings(ipck = TRUE)") interface.installed_packages() # print welcome message sys.stdout.write(interface.greeting())
def start(self): # default history file histfile = FileHistory('.shad0w_history') # do what prompts do self.set_autocompletes() try: self.prompt_session = PromptSession(history=histfile) 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 = self.prompt_session.prompt( 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": input = self.prompt_session.prompt( ANSI(self.active_domain_prompt % (username, domain, machine)), completer=self.autocomplete, complete_style=CompleteStyle.READLINE_LIKE) else: input = self.prompt_session.prompt( ANSI(self.active_prompt % (username, machine)), completer=self.autocomplete, complete_style=CompleteStyle.READLINE_LIKE) # handle the input we just recived try: 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()
def result_from_prompt(message, add_history=1): if not self.initialized: self.app_initialize(mp) message = mp.default_prompt self.initialized = True sys.stdout.write("\n") else: if mp.interrupted: mp.interrupted = False if mp.insert_new_line: sys.stdout.write("\n") mp.add_history = add_history == 1 text = None # a hack to stop rtichoke when exiting if an error occurs in process_events # however, please note that it doesn't in general guarantee to work # the best practice is to restart rtichoke mp.app._is_running = False set_event_loop(None) while text is None: try: if message == mp.default_prompt: mp.prompt_mode = "r" elif BROWSE_PATTERN.match(message): level = BROWSE_PATTERN.match(message).group(1) mp.prompt_mode = "browse" mp.set_prompt_mode_message( "browse", ANSI(mp.browse_prompt.format(level))) else: # invoked by `readline` mp.prompt_mode = "readline" mp.set_prompt_mode_message("readline", ANSI(message)) text = mp.run() except Exception as e: if isinstance(e, EOFError): # todo: confirmation in "r" mode return None else: print("unexpected error was caught.") print("please report to https://github.com/randy3k/rtichoke for such error.") print(e) import traceback traceback.print_exc() return None except KeyboardInterrupt: if mp.prompt_mode in ["readline"]: mp.interrupted = True api.interrupts_pending(True) api.check_user_interrupt() return text
def __init(self, **kwargs): """ Initialize the parent console with commands and modules. """ Console._dev_mode = kwargs.pop("dev", False) # setup banners bsrc = self._sources("banners") if bsrc is not None: print_formatted_text("") # display a random banner from the banners folder get_banner_func = kwargs.get('get_banner_func', get_banner) banner_colors = kwargs.get('banner_section_styles', {}) text = get_banner_func(self.appdispname, bsrc, styles=banner_colors) if text: print_formatted_text(ANSI(text)) # display a random quote from quotes.csv (in the banners folder) get_quote_func = kwargs.get('get_quote_func', get_quote) try: text = get_quote_func(os.path.join(bsrc, "quotes.csv")) if text: print_formatted_text(ANSI(text)) except ValueError: pass # setup libraries lsrc = self._sources("libraries") if lsrc is not None: if isinstance(lsrc, str): lsrc = [lsrc] if isinstance(lsrc, (list, tuple, set)): for lib in map(lambda p: os.path.abspath(p), lsrc[::-1]): sys.path.insert(0, lib) # setup entities load_entities( [BaseModel, Command, Console, Model, Module, StoreExtension], *self._sources("entities"), include_base=kwargs.get("include_base", True), select=kwargs.get("select", {'command': Command._functionalities}), exclude=kwargs.get("exclude", {}), backref=kwargs.get("backref", BACK_REFERENCES), docstr_parser=kwargs.get("docstr_parser", parse_docstring), ) Console._storage.models = Model.subclasses + BaseModel.subclasses # display module stats print_formatted_text(FormattedText([("#00ff00", Module.get_summary()) ])) # setup the prompt message self.message.insert(0, ('class:appname', self.appname)) # display warnings self.reset() if Entity.has_issues(): self.logger.warning("There are some issues ; use 'show issues' to " "see more details") # console's components back-referencing for attr in ["_files", "_jobs"]: setattr(getattr(Console, attr), "console", self)
def message(): if hasattr(session.current_mode, "get_message"): return ANSI(vi_mode_prompt() + session.current_mode.get_message()) elif hasattr(session.current_mode, "message"): message = session.current_mode.message if callable(message): return ANSI(vi_mode_prompt() + message()) else: return ANSI(vi_mode_prompt() + message) else: return ""
def checklist_text(self): s = [] idx = 0 for (item, level) in self.checklist.items(with_level=True): if item.unchecked or self.show_completed: if idx == self.cursor_position.y: ansi0, ansi1 = '\x1b[7m', '\x1b[0m' else: ansi0, ansi1 = '', '' if hasattr(item, 'items'): ansi0, ansi1 = '\x1b[1m', '\x1b[0m' else: ansi2, ansi3 = '', '' idx += 1 s.append("{ansi0}[{checked}] {indent}{name}{ansi1}".format( ansi0=ansi0, ansi1=ansi1, checked='x' if item.checked else ' ', indent=' ' * 2 * level, name=item.name)) if len(s) > 0: return ANSI("\n".join(s)) else: return '[🥇]'
def getinput_autocompleted(name, commands, variables, liners): text = session.prompt(ANSI(name), completer=MyCompleter(commands, variables, liners), complete_while_typing=True, complete_in_thread=True, complete_style=CompleteStyle.READLINE_LIKE) return text
def choose_version(assets): '''choose a version from assets list''' versions = list(map(lambda item: item['version'], assets)) # print(versions) values = list(map(lambda item: (item, item), versions)) rdo = NewRadioList(values) def do_exit(event): # get_app().exit() event.app.exit(result=rdo.current_value) def do_up_down(event): print(event) pass bindings = KeyBindings() bindings.add('enter')(do_exit) app_bindings = merge_key_bindings([load_key_bindings(), bindings]) selected = Application(layout=Layout(rdo), key_bindings=app_bindings).run() if selected in versions: print('your choice is:', end=' ') # refer: https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/examples/print-text/ansi.py print_formatted_text(ANSI('\x1b[91m{0}'.format(selected))) return selected else: print('canceled')
def main(): style = Style.from_dict({ 'hello': '#ff0066', 'world': '#44ff44 italic', }) # Print using a a list of text fragments. text_fragments = FormattedText([ ('class:hello', 'Hello '), ('class:world', 'World'), ('', '\n'), ]) print(text_fragments, style=style) # Print using an HTML object. print(HTML( '<hello>hello</hello> <world>world</world>\n'), style=style) # Print using an HTML object with inline styling. print(HTML( '<style fg="#ff0066">hello</style> ' '<style fg="#44ff44"><i>world</i></style>\n')) # Print using ANSI escape sequences. print(ANSI( '\x1b[31mhello \x1b[32mworld\n'))
def run(self): self.console.root.interfaces data = [[ "ESSID", "BSSID", "Channel", "Power", "Enc", "Cipher", "Auth", "Password", "Stations" ]] # parse targets from the state variable for essid, target in sorted(self.console.state['TARGETS'].items(), key=lambda x: x[0]): i = self.console.state['INTERFACES'] c = any(x[1] == essid for x in i.values()) rows = [] # for each target, get the value from its associated dictionary for i, h in enumerate(data[0]): rows.append([""] * len(data[0])) v = target[h.lower()] if isinstance(v, (tuple, list)): for j in range(len(v) - 1): rows.append([""] * len(data[0])) else: v = [v] for j, sv in enumerate(v): sv = sv or "" if c: sv = colored(sv, attrs=['bold']) rows[j][i] = sv for r in rows: if all(v == "" for v in r): continue data.append(r) if len(data) > 1: t = BorderlessTable(data, "Available Targets") print_formatted_text(ANSI(t.table)) else: self.logger.warning("No target available yet")
def patched_handle_exception(self, e): j = KosmosShellConfig.j # Instead of just calling ``traceback.format_exc``, we take the # traceback and skip the bottom calls of this framework. t, v, tb = sys.exc_info() output = self.app.output # Required for pdb.post_mortem() to work. sys.last_type, sys.last_value, sys.last_traceback = t, v, tb # loop until getting actual traceback (without internal ptpython part) last_stdin_tb = tb while tb: if tb.tb_frame.f_code.co_filename == "<stdin>": last_stdin_tb = tb tb = tb.tb_next logdict = j.core.tools.log(tb=last_stdin_tb, level=50, exception=e, stdout=False) formatted_tb = j.core.tools.log2str(logdict, data_show=True, replace=True) print_formatted_text(ANSI(formatted_tb)) output.write("%s\n" % e) output.flush()
def test_ansi_256_color(): assert to_formatted_text(ANSI("\x1b[38;5;124mtest")) == [ ("#af0000", "t"), ("#af0000", "e"), ("#af0000", "s"), ("#af0000", "t"), ]
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> ") prompt = prompt.replace("\\x1b", "\x1b") return ANSI(prompt)
def patched_handle_exception(self, e): """ a new handler for ptpython repl exceptions it will call excepthook after ommitting all this framework's calls from traceback for the original, see ptpython.repl.PythonInput._handle_exception """ output = self.app.output t, v, tb = sys.exc_info() # Required for pdb.post_mortem() to work. sys.last_type, sys.last_value, sys.last_traceback = t, v, tb # loop until getting actual traceback last_stdin_tb = tb while tb: if tb.tb_frame.f_code.co_filename == "<stdin>": last_stdin_tb = tb tb = tb.tb_next # except hook does not work as expected sys.excepthook(t, v, last_stdin_tb) # just print formatted exception for now formatted = better_exceptions.format_exception(t, v, last_stdin_tb) print_formatted_text(ANSI(formatted)) output.write("%s\n" % e) output.flush()
def result_from_prompt(message, add_history=1): if not self.initialized: self.app_initialize(mp) message = mp.default_prompt self.initialized = True sys.stdout.write("\n") else: if mp.interrupted: mp.interrupted = False if mp.insert_new_line: sys.stdout.write("\n") mp.add_history = add_history == 1 text = None while text is None: try: if message == mp.default_prompt: mp.prompt_mode = "r" elif BROWSE_PATTERN.match(message): level = BROWSE_PATTERN.match(message).group(1) mp.prompt_mode = "browse" mp.set_prompt_mode_message( "browse", ANSI(mp.browse_prompt.format(level))) else: # invoked by `readline` mp.prompt_mode = "readline" mp.set_prompt_mode_message("readline", ANSI(message)) text = mp.run() except Exception as e: if isinstance(e, EOFError): # todo: confirmation in "r" mode return None else: print(e) return None except KeyboardInterrupt: if mp.prompt_mode in ["readline"]: mp.interrupted = True api.interrupts_pending(True) api.check_user_interrupt() return text
def main(): # Example 1: fixed text. text = prompt('Say something: ', bottom_toolbar='This is a toolbar') print('You said: %s' % text) # Example 2: fixed text from a callable: def get_toolbar(): return 'Bottom toolbar: time=%r' % time.time() text = prompt('Say something: ', bottom_toolbar=get_toolbar, refresh_interval=.5) print('You said: %s' % text) # Example 3: Using HTML: text = prompt( 'Say something: ', bottom_toolbar=HTML( '(html) <b>This</b> <u>is</u> a <style bg="ansired">toolbar</style>' )) print('You said: %s' % text) # Example 4: Using ANSI: text = prompt( 'Say something: ', bottom_toolbar=ANSI( '(ansi): \x1b[1mThis\x1b[0m \x1b[4mis\x1b[0m a \x1b[91mtoolbar')) print('You said: %s' % text) # Example 5: styling differently. style = Style.from_dict({ 'bottom-toolbar': '#aaaa00 bg:#ff0000', 'bottom-toolbar.text': '#aaaa44 bg:#aa4444', }) text = prompt('Say something: ', bottom_toolbar='This is a toolbar', style=style) print('You said: %s' % text) # Example 6: Using a list of tokens. def get_bottom_toolbar(): return [ ('', ' '), ('bg:#ff0000 fg:#000000', 'This'), ('', ' is a '), ('bg:#ff0000 fg:#000000', 'toolbar'), ('', '. '), ] text = prompt('Say something: ', bottom_toolbar=get_bottom_toolbar) print('You said: %s' % text) # Example 7: multiline fixed text. text = prompt('Say something: ', bottom_toolbar='This is\na multiline toolbar') print('You said: %s' % text)
def run(self, key, value=None): if key == "options": if value is None: print_formatted_text(ANSI(str(self.config))) else: c = Config() c.prefix = "Module" c[self.config.option(value)] = self.config[value] print_formatted_text(ANSI(str(c))) elif key == "info": i = self.console.module.get_info(("fullpath|path", "description"), ("author", "email", "version"), ("comments",), ("options",), show_all=True) if len(i.strip()) != "": print_formatted_text(i) elif key == "issues": t = Entity.get_issues() if len(t) > 0: print_formatted_text(t)
def app_initialize(self, mp): if sys.platform.startswith('win'): callbacks.ENCODING = interface.encoding() if interface.get_option("rice.editing_mode", "emacs") in ["vim", "vi"]: mp.app.editing_mode = EditingMode.VI else: mp.app.editing_mode = EditingMode.EMACS color_scheme = interface.get_option("rice.color_scheme", "native") mp.style = style_from_pygments(get_style_by_name(color_scheme)) mp.app.auto_indentation = interface.get_option("rice.auto_indentation", True) mp.app.tab_size = int(interface.get_option("rice.tab_size", 4)) mp.complete_while_typing = interface.get_option("rice.complete_while_typing", True) prompt = interface.get_option("rice.prompt", None) if prompt: mp.set_prompt_mode_message("r", ANSI(prompt)) else: sys_prompt = interface.get_option("prompt") if sys_prompt == "> ": prompt = PROMPT else: prompt = sys_prompt mp.default_prompt = prompt mp.set_prompt_mode_message("r", ANSI(prompt)) interface.set_option("prompt", prompt) shell_prompt = interface.get_option("rice.shell_prompt", SHELL_PROMPT) mp.set_prompt_mode_message("shell", ANSI(shell_prompt)) set_width_on_resize = interface.get_option("setWidthOnResize", True) mp.auto_width = interface.get_option("rice.auto_width", set_width_on_resize) if mp.auto_width: interface.set_option("width", mp.app.output.get_size().columns) # necessary on windows interface.set_option("menu.graphics", False) # print welcome message sys.stdout.write(interface.r_version())
def example_3(): """ Using ANSI for the formatting. """ answer = prompt( ANSI("\x1b[31mjohn\x1b[0m@" "\x1b[44mlocalhost\x1b[0m:" "\x1b[4m/user/john\x1b[0m" "# ")) print("You said: %s" % answer)
def example_3(): """ Using ANSI for the formatting. """ answer = prompt( ANSI('\x1b[31mjohn\x1b[0m@' '\x1b[44mlocalhost\x1b[0m:' '\x1b[4m/user/john\x1b[0m' '# ')) print('You said: %s' % answer)
def run(self, key, value=None): if key == "files": if value is None: data = [["Path", "Size"]] p = Path(self.config.option("WORKSPACE").value) for f in self.console._files.list: data.append([f, human_readable_size(p.joinpath(f).size)]) print_formatted_text( BorderlessTable(data, "Files from the workspace")) elif self.config.option("TEXT_VIEWER").value: self.console._files.view(value) elif key == "issues": t = Entity.get_issues() if len(t) > 0: print_formatted_text(t) elif key == "modules": h = Module.get_help(value) if h.strip() != "": print_formatted_text(h) else: self.logger.warning("No module loaded") elif key == "options": if value is None: print_formatted_text(ANSI(str(self.config))) else: c = Config() c[self.config.option(value)] = self.config[value] print_formatted_text(ANSI(str(c))) elif key == "projects": if value is None: data = [["Name"]] for p in projects(self): data.append([p]) print_formatted_text(BorderlessTable(data, "Existing projects")) else: print_formatted_text(value) elif key == "sessions": data = [["ID", "Description"]] for i, s in self.console._sessions: data.append([str(i), getattr(s, "description", "<undefined>")]) print_formatted_text(BorderlessTable(data, "Open sessions"))
def __init__(self, title, const_value=None, label_col="cyan", extend_label_width=False): if title is not None: self.name = title.lower().replace(" ", "_") self.title_label = Label(text=title + ": ", dont_extend_width=not extend_label_width, style="bold %s" % label_col) if const_value is not None: self.value_label = Label(text=ANSI(const_value))
def xlogin(self, prompt='\\l \\u@\\h:\\d> '): user = self.options['login']['user'] or '(none)' host = self.options['host'] or '(none)' dbname = self.options['database'] or '(none)' name = self.options['name'] prompt = prompt.replace('\\l', name) prompt = prompt.replace('\\u', user.lower()) prompt = prompt.replace('\\h', host) prompt = prompt.replace('\\d', dbname.lower()) prompt = prompt.replace('\\_', ' ') return ANSI(prompt)
def bottom_toolbar_async(self): rv = None try: word = self.buffer.document.get_word_under_cursor(WORD=True) if word: resp = self.engine.get_type(word, False) if resp.success: rv = ANSI(hl(resp.content.strip(), self.config)) except NameError: pass self.bottom_text = rv get_app().invalidate()
def _prompt(self): commands = self.commands.get_all() reserved_words_completer = WordCompleter(commands) try: while not self._stop: user_input = prompt(ANSI('\x1b[35mradio> '), completer=reserved_words_completer) if user_input and not self._stop: self._execute(user_input) except EOFError: self.stop() except KeyboardInterrupt: self.stop() except ValueError: pass