示例#1
0
def main():
    # Tell prompt_toolkit to use the asyncio event loop.
    use_asyncio_event_loop()
    with patch_stdout():
        shell_task = asyncio.ensure_future(interactive_shell())
        loop.run_until_complete(shell_task)
        print('Quitting event loop. Bye.')
示例#2
0
def main(network, no_dns, f_interface):
    # Tell prompt_toolkit to use the asyncio event loop.
    try:
        with patch_stdout():

            loop = asyncio.get_event_loop()
            use_asyncio_event_loop()

            interface = netcheck.get_netdevice(
                network.split('/')[0])  # cut off cidr netmask
            if not interface:
                if f_interface:
                    interface = f_interface
                else:
                    raise Exception(
                        'Can not continue without interface. Try to specify using "-i" argument'
                    )
            print('interface is %s' % interface)
            # SETUP SHELL
            # add hostnames add completer
            hosts_d = {
                ip: hostname
                for ip, hostname in netcheck.get_hostnames(
                    network, filter_hosts=not no_dns)
            }
            whosonline_completer.words += list(hosts_d.values())

            # start shell
            shell_task = asyncio.ensure_future(
                interactive_shell(loop, network, hosts_d, interface, no_dns))
            loop.run_until_complete(shell_task)
    except Exception as e:
        print(e)
示例#3
0
文件: cli.py 项目: vivisect/synapse
    async def __anit__(self, item, outp=None, **locs):

        await s_base.Base.__anit__(self)

        # Tell prompt_toolkit to use the asyncio event loop.
        use_asyncio_event_loop()

        if outp is None:
            outp = s_output.OutPut()

        self.outp = outp
        self.locs = locs
        self.cmdtask = None  # type: asyncio.Task

        self.sess = None
        self.vi_mode = _inputrc_enables_vi_mode()

        self.item = item    # whatever object we are commanding

        self.echoline = False

        if isinstance(self.item, s_base.Base):
            self.item.onfini(self._onItemFini)

        self.cmds = {}
        self.cmdprompt = 'cli> '

        self.addCmdClass(CmdHelp)
        self.addCmdClass(CmdQuit)
        self.addCmdClass(CmdLocals)
示例#4
0
    async def read_input(self):
        """
        Coroutine reading the user's keyboard input and
        transforming it into the CMessage.
        If '//exit' is read here, the program exits.
        """
        use_asyncio_event_loop()

        while True:

            with patch_stdout():
                message = await prompt(
                    f'> {self.name}({self.address}:{self.port}): ',
                    async_=True)

            if message == '//exit':

                logging.info(f'{self.logical_clock}: Exiting...')
                self.exiting = True

                if self.next_node_writer is not None:
                    self.next_node_writer.close()
                    await self.next_node_writer.wait_closed()

                return

            umsg = self.craft_message(MessageType.user_message, message)
            await self.send_user_message(umsg)
示例#5
0
def prompt_init():
    """
    Initialize prompt
    """
    if hasattr(prompt_init, "_called"):
        return
    prompt_init._called = True
    use_asyncio_event_loop()
示例#6
0
def main():
    clear_screen()
    print(Banner)
    for plugin in PluginsLoaded:
        print("Loaded plugin {}".format(plugin))
    use_asyncio_event_loop()
    loop = asyncio.get_event_loop()
    deadman_task = loop.create_task(relock_wallet_if_timed_out())
    loop.run_until_complete(wallet_repl())
示例#7
0
文件: main.py 项目: jlmitch5/druid
def main():
    logging.config.dictConfig({
        'version': 1,
        'formatters': {
            'detailed': {
                'class':
                'logging.Formatter',
                'format':
                '%(asctime)s %(name)-15s %(levelname)-8s'
                '%(processName)-10s %(message)s'
            },
        },
        'handlers': {
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'druid.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
        },
        'loggers': {
            'crowlib': {
                'handlers': ['file'],
            },
        },
        'root': {
            'level': 'DEBUG',
            'handlers': [],
        },
    })

    global crow
    loop = asyncio.get_event_loop()

    try:
        crow = crowlib.connect()
    except ValueError as err:
        print(err)
        exit()

    # run script passed from command line
    if len(sys.argv) == 2:
        crowlib.execute(crow.write, myprint, sys.argv[1])

    use_asyncio_event_loop()

    with patch_stdout():
        background_task = asyncio.gather(printer(), return_exceptions=True)
        loop.run_until_complete(shell())
        background_task.cancel()
        loop.run_until_complete(background_task)

    crow.close()
    exit()
示例#8
0
async def shell_loop(context: AttackContext):
    use_asyncio_event_loop()
    history_dir = Path(appdirs.user_data_dir('python-xcat'))
    if not history_dir.exists():
        history_dir.mkdir(parents=True)
    history = FileHistory(history_dir / 'history')
    session = PromptSession(history=history)

    commands: Dict[str, BaseCommand] = {
        c.name: c(context)
        for c in BaseCommand.__subclasses__()
    }

    for c in BaseCommand.__subclasses__():
        for alias in c.alias:
            commands[alias] = commands[c.name]
    completer = WordCompleter(commands.keys(),
                              meta_dict={
                                  name: command.help_display()
                                  for name, command in commands.items()
                              })
    style = Style.from_dict({'prompt': '#884444', 'dollar': '#00aa00'})

    while True:
        user_input = await session.prompt(
            [('class:prompt', 'XCat'), ('class:dollar', '$ ')],
            style=style,
            async_=True,
            completer=completer,
            auto_suggest=AutoSuggestFromHistory())

        split_input = shlex.split(user_input)
        if not split_input:
            continue

        name, args = split_input[0], split_input[1:]

        if name not in commands:
            print(f'Unknown command {name}. Use "help" to get help')
            continue

        command = commands[name]

        if not command.has_features(context.features):
            print(click.style('Error: ', 'red'), end='')
            print(f'Cannot use {name} as not all features are '
                  f'present in this injection')
            if command.required_features:
                print('Required features: ', end='')
                print(click.style(', '.join(command.required_features), 'red'))
                print('Use toggle_feature to force these on')
        else:
            await command.run(args)
def main():
    # Tell prompt_toolkit to use the asyncio event loop.
    use_asyncio_event_loop()

    with patch_stdout():
        shell_task = asyncio.ensure_future(interactive_shell())
        background_task = asyncio.gather(print_counter(), return_exceptions=True)

        loop.run_until_complete(shell_task)
        background_task.cancel()
        loop.run_until_complete(background_task)
        print('Quitting event loop. Bye.')
示例#10
0
文件: repl.py 项目: Jwhiles/druid
def main(script=None):
    logging.config.dictConfig({
        'version': 1,
        'formatters': {
            'detailed': {
                'class':
                'logging.Formatter',
                'format':
                '%(asctime)s %(name)-15s %(levelname)-8s'
                '%(processName)-10s %(message)s'
            },
        },
        'handlers': {
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'druid.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
        },
        'loggers': {
            'crowlib': {
                'handlers': ['file'],
            },
        },
        'root': {
            'level': 'DEBUG',
            'handlers': [],
        },
    })

    crowreconnect(errmsg="crow disconnected")

    # run script passed from command line
    if script:
        if is_connected == False:
            print("no crow device found. exiting.")
            sys.exit(1)
        crowlib.execute(crow.write, myprint, script)

    loop = asyncio.get_event_loop()

    use_asyncio_event_loop()

    with patch_stdout():
        background_task = asyncio.gather(printer(), return_exceptions=True)
        loop.run_until_complete(shell())
        background_task.cancel()

    if is_connected:
        crow.close()
    sys.exit()
示例#11
0
async def create_full_prompt(process):
    # Mandatory from prompt_toolkit
    context_id = None
    use_asyncio_event_loop()

    # Size getter
    def get_size():
        width, height, _, _ = process.get_terminal_size()
        return Size(rows=height, columns=width)

    # Set up resize event
    def size_changed(*_):
        with context(context_id):
            get_app()._on_resize()

    process.terminal_size_changed = size_changed

    # Prepare input stream
    vt100_input = create_pipe_input()
    type(vt100_input).responds_to_cpr = True
    await process.redirect_stdin(vt100_input._w)

    # Prepare output stream
    process.stdout.encoding = "utf-8"
    process.stdout.flush = lambda: None
    vt100_output = Vt100_Output(process.stdout,
                                get_size,
                                term=process.get_terminal_type())

    # Define local print

    def sprint(*args, **kwargs):
        kwargs.setdefault("output", vt100_output)
        print_formatted_text(*args, **kwargs)

    async def aprint(*args, **kwargs):
        sprint(*args, **kwargs)
        await process.stdout.drain()

    # Define local prompt

    async def aprompt(*args, **kwargs):
        nonlocal context_id
        kwargs['async_'] = True
        kwargs['input'] = vt100_input
        kwargs['output'] = vt100_output
        with context() as context_id:
            return await prompt(*args, **kwargs)

    aprompt.get_size = vt100_output.get_size
    aprint.sprint = sprint
    return aprint, aprompt
def main():
    # Tell prompt_toolkit to use the asyncio event loop.
    use_asyncio_event_loop()

    with patch_stdout():
        shell_task = asyncio.ensure_future(interactive_shell())
        background_task = asyncio.gather(print_counter(),
                                         return_exceptions=True)

        loop.run_until_complete(shell_task)
        background_task.cancel()
        loop.run_until_complete(background_task)
        print('Quitting event loop. Bye.')
示例#13
0
    def __call__(self):
        """function startin main asyncio loop"""
        async def sig_exit():
            self.log.info('Why are you so?')

        loop = asyncio.get_event_loop()

        for sig_name in ('SIGINT', 'SIGTERM'):
            loop.add_signal_handler(getattr(signal, sig_name),
                                    lambda: asyncio.ensure_future(sig_exit()))
        use_asyncio_event_loop()
        shell_task = asyncio.gather(self.start())
        with patch_stdout():
            loop.run_until_complete(shell_task)
            for task in asyncio.Task.all_tasks(loop=loop):
                if task is not asyncio.Task.current_task():
                    task.cancel()
示例#14
0
def main(script=None):
    try:
        logging.config.dictConfig(log_config)
    except ValueError:
        print('could not configure file logging (insufficient permissions?)')

    loop = asyncio.get_event_loop()
    use_asyncio_event_loop()
    with patch_stdout():
        with Crow() as crow:
            shell = Druid(crow)
            crow.reconnect(err_event=True)
            background_task = asyncio.gather(
                shell.background(),
                return_exceptions=True,
            )
            loop.run_until_complete(shell.foreground())
            background_task.cancel()
示例#15
0
    async def __anit__(self, item, outp=None, **locs):

        await s_base.Base.__anit__(self)

        # Tell prompt_toolkit to use the asyncio event loop.
        use_asyncio_event_loop()

        if outp is None:
            outp = s_output.OutPut()

        self.outp = outp
        self.locs = locs
        self.cmdtask = None  # type: asyncio.Task

        self.sess = None
        self.vi_mode = _inputrc_enables_vi_mode()

        self.item = item  # whatever object we are commanding

        self.echoline = False
        self.colorsenabled = False

        if isinstance(self.item, s_base.Base):
            self.item.onfini(self._onItemFini)

        self.locs['syn:local:version'] = s_version.verstring

        if isinstance(self.item, s_telepath.Proxy):
            version = self.item._getSynVers()
            if version is None:  # pragma: no cover
                self.locs[
                    'syn:remote:version'] = 'Remote Synapse version unavailable'
            else:
                self.locs['syn:remote:version'] = '.'.join(
                    [str(v) for v in version])

        self.cmds = {}
        self.cmdprompt = 'cli> '

        self.addCmdClass(CmdHelp)
        self.addCmdClass(CmdQuit)
        self.addCmdClass(CmdLocals)
示例#16
0
def main():
    global crow
    loop = asyncio.get_event_loop()

    try:
        crow = crowlib.connect()
    except ValueError as err:
        print(err)
        exit()

    # run script passed from command line
    if len(sys.argv) == 2:
        crowlib.execute(crow.write, myprint, sys.argv[1])

    use_asyncio_event_loop()

    with patch_stdout():
        background_task = asyncio.gather(printer(), return_exceptions=True)
        loop.run_until_complete(shell())
        background_task.cancel()
        loop.run_until_complete(background_task)

    crow.close()
    exit()
from prompt_toolkit import prompt
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop

# Tell prompt_toolkit to use the asyncio event loop.
use_asyncio_event_loop()

import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner


# http://python-prompt-toolkit.readthedocs.io/en/stable/pages/building_prompts.html#input-validation
class NumberValidator(Validator):
    def validate(self, document):
        text = document.text

        if text and not text.isdigit():
            i = 0

            # Get index of fist non numeric character.
            # We want to move the cursor here.
            for i, c in enumerate(text):
                if not c.isdigit():
                    break

            raise ValidationError(
                message='This input contains non-numeric characters',
                cursor_position=i)

示例#18
0
 def __init__(self, ignore_sigint=True):
     use_asyncio_event_loop()
     self.completer = self._make_completer()
     self.session = None
     self._ignore_sigint = ignore_sigint
     self._currently_running_task = None
示例#19
0
    def init_prompt_toolkit_cli(self):
        if self.simple_prompt or ('JUPYTER_CONSOLE_TEST' in os.environ):
            # Simple restricted interface for tests so we can find prompts with
            # pexpect. Multi-line input not supported.
            async def prompt():
                prompt = 'In [%d]: ' % self.execution_count
                raw = await async_input(prompt)
                return raw

            self.prompt_for_code = prompt
            self.print_out_prompt = \
                lambda: print('Out[%d]: ' % self.execution_count, end='')
            return

        kb = KeyBindings()
        insert_mode = vi_insert_mode | emacs_insert_mode

        @kb.add("enter",
                filter=(has_focus(DEFAULT_BUFFER)
                        & ~has_selection
                        & insert_mode))
        def _(event):
            b = event.current_buffer
            d = b.document
            if not (d.on_last_line or d.cursor_position_row >=
                    d.line_count - d.empty_line_count_at_the_end()):
                b.newline()
                return

            # Pressing enter flushes any pending display. This also ensures
            # the displayed execution_count is correct.
            self.handle_iopub()

            more, indent = self.check_complete(d.text)

            if (not more) and b.accept_handler:
                b.validate_and_handle()
            else:
                b.insert_text('\n' + indent)

        @kb.add("c-c", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        @kb.add("c-\\", filter=has_focus(DEFAULT_BUFFER))
        def _(event):
            raise EOFError

        @kb.add("c-z",
                filter=Condition(lambda: suspend_to_background_supported()))
        def _(event):
            event.cli.suspend_to_background()

        @kb.add("c-o", filter=(has_focus(DEFAULT_BUFFER) & emacs_insert_mode))
        def _(event):
            event.current_buffer.insert_text("\n")

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for _, _, cell in self.history_manager.get_tail(
                self.history_load_length, include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append_string(cell)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
            Token.OutPrompt: '#ff2200',
            Token.OutPromptNum: '#ff0000 bold',
            Token.RemotePrompt: '#999900',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = merge_styles([
            style_from_pygments_cls(style_cls),
            style_from_pygments_dict(style_overrides),
        ])

        editing_mode = getattr(EditingMode, self.editing_mode.upper())
        langinfo = self.kernel_info.get('language_info', {})
        lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))

        # If enabled in the settings, highlight matching brackets
        # when the DEFAULT_BUFFER has the focus
        input_processors = [
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=has_focus(DEFAULT_BUFFER) & ~is_done
                & Condition(lambda: self.highlight_matching_brackets))
        ]

        # Tell prompt_toolkit to use the asyncio event loop.
        # Obsolete in prompt_toolkit.v3
        if not PTK3:
            use_asyncio_event_loop()

        self.pt_cli = PromptSession(
            message=(lambda: PygmentsTokens(self.get_prompt_tokens())),
            multiline=True,
            complete_style=self.pt_complete_style,
            editing_mode=editing_mode,
            lexer=PygmentsLexer(get_pygments_lexer(lexer)),
            prompt_continuation=(
                lambda width, lineno, is_soft_wrap: PygmentsTokens(
                    self.get_continuation_tokens(width))),
            key_bindings=kb,
            history=history,
            completer=JupyterPTCompleter(self.Completer),
            enable_history_search=True,
            style=style,
            input_processors=input_processors,
            color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),
        )
示例#20
0
async def accept_taa(ledger: BaseLedger,
                     taa_info,
                     provision: bool = False) -> bool:
    """Perform TAA acceptance."""

    if not sys.stdout.isatty():
        LOGGER.warning("Cannot accept TAA without interactive terminal")
        return False

    mechanisms = taa_info["aml_record"]["aml"]
    allow_opts = OrderedDict([
        (
            "wallet_agreement",
            ("Accept the transaction author agreement and store the " +
             "acceptance in the wallet"),
        ),
        (
            "on_file",
            ("Acceptance of the transaction author agreement is on file " +
             "in my organization"),
        ),
    ])
    if not provision:
        allow_opts["for_session"] = (
            "Accept the transaction author agreement for the duration of " +
            "the current session")

    found = []
    for opt in allow_opts:
        if opt in mechanisms:
            found.append(opt)

    md = markdown.Markdown()
    taa_html = md.convert(taa_info["taa_record"]["text"])
    taa_html = re.sub(r"<h[1-6]>(.*?)</h[1-6]>",
                      r"<p><strong>\1</strong></p>\n", taa_html)
    taa_html = re.sub(r"<li>(.*?)</li>", r" - \1", taa_html)

    taa_html = ("\n<strong>Transaction Author Agreement version " +
                taa_info["taa_record"]["version"] + "</strong>\n\n" + taa_html)

    # setup for prompt_toolkit
    use_asyncio_event_loop()

    prompt_toolkit.print_formatted_text(HTML(taa_html))

    opts = []
    num_mechanisms = {}
    for idx, opt in enumerate(found):
        num_mechanisms[str(idx + 1)] = opt
        opts.append(f" {idx+1}. {allow_opts[opt]}")
    opts.append(" X. Skip the transaction author agreement")
    opts_text = "\nPlease select an option:\n" + "\n".join(opts) + "\n[1]> "

    while True:
        try:
            opt = await prompt_toolkit.prompt(opts_text, async_=True)
        except EOFError:
            return False
        if not opt:
            opt = "1"
        opt = opt.strip()
        if opt in ("x", "X"):
            return False
        if opt in num_mechanisms:
            mechanism = num_mechanisms[opt]
            break

    await ledger.accept_txn_author_agreement(taa_info["taa_record"], mechanism)

    return True
示例#21
0
def prompt_init():
    if hasattr(prompt_init, "_called"):
        return
    prompt_init._called = True
    use_asyncio_event_loop()
示例#22
0
def embed(globals=None,
          locals=None,
          configure=None,
          vi_mode=False,
          history_filename=None,
          title=None,
          startup_paths=None,
          patch_stdout=False,
          return_asyncio_coroutine=False):
    """
    Call this to embed  Python shell at the current point in your program.
    It's similar to `IPython.embed` and `bpython.embed`. ::

        from prompt_toolkit.contrib.repl import embed
        embed(globals(), locals())

    :param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
    :param configure: Callable that will be called with the `PythonRepl` as a first
                      argument, to trigger configuration.
    :param title: Title to be displayed in the terminal titlebar. (None or string.)
    """
    assert configure is None or callable(configure)

    # Default globals/locals
    if globals is None:
        globals = {
            '__name__': '__main__',
            '__package__': None,
            '__doc__': None,
            '__builtins__': six.moves.builtins,
        }

    locals = locals or globals

    def get_globals():
        return globals

    def get_locals():
        return locals

    # Create eventloop.
    if return_asyncio_coroutine:
        use_asyncio_event_loop()

    # Create REPL.
    repl = PythonRepl(get_globals=get_globals,
                      get_locals=get_locals,
                      vi_mode=vi_mode,
                      history_filename=history_filename,
                      startup_paths=startup_paths)

    if title:
        repl.terminal_title = title

    if configure:
        configure(repl)

    app = repl.app

    # Start repl.
    patch_context = app.patch_stdout_context(
    ) if patch_stdout else DummyContext()

    if return_asyncio_coroutine:  # XXX

        def coroutine():
            with patch_context:
                for future in app.run_async():
                    yield future

        return coroutine()
    else:
        with patch_context:
            repl.run()
"""
from __future__ import unicode_literals

from prompt_toolkit.contrib.telnet.server import TelnetServer
from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop
from prompt_toolkit.shortcuts import PromptSession

import logging
import asyncio

# Set up logging
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)

# Tell prompt_toolkit to use the asyncio event loop.
use_asyncio_event_loop()


async def interact(connection):
    session = PromptSession(output=connection.vt100_output, input=connection.vt100_input)

    connection.erase_screen()
    connection.send('Welcome!\n')

    # Ask for input.
    result = await session.prompt(message='Say something: ', async_=True)

    # Send output.
    connection.send('You said: {}\n'.format(result))
    connection.send('Bye.\n')
示例#24
0
def embed(globals=None, locals=None, configure=None,
          vi_mode=False, history_filename=None, title=None,
          startup_paths=None, patch_stdout=False, return_asyncio_coroutine=False):
    """
    Call this to embed  Python shell at the current point in your program.
    It's similar to `IPython.embed` and `bpython.embed`. ::

        from prompt_toolkit.contrib.repl import embed
        embed(globals(), locals())

    :param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
    :param configure: Callable that will be called with the `PythonRepl` as a first
                      argument, to trigger configuration.
    :param title: Title to be displayed in the terminal titlebar. (None or string.)
    """
    assert configure is None or callable(configure)

    # Default globals/locals
    if globals is None:
        globals = {
            '__name__': '__main__',
            '__package__': None,
            '__doc__': None,
            '__builtins__': six.moves.builtins,
        }

    locals = locals or globals

    def get_globals():
        return globals

    def get_locals():
        return locals

    # Create eventloop.
    if return_asyncio_coroutine:
        use_asyncio_event_loop()

    # Create REPL.
    repl = PythonRepl(get_globals=get_globals, get_locals=get_locals, vi_mode=vi_mode,
                      history_filename=history_filename, startup_paths=startup_paths)

    if title:
        repl.terminal_title = title

    if configure:
        configure(repl)

    app = repl.app

    # Start repl.
    patch_context = patch_stdout_context() if patch_stdout else DummyContext()

    if return_asyncio_coroutine: # XXX
        def coroutine():
            with patch_context:
                while True:
                    iterator = iter(app.run_async().to_asyncio_future())
                    try:
                        while True:
                            yield next(iterator)
                    except StopIteration as exc:
                        text = exc.args[0]
                    repl._process_text(text)
        return coroutine()
    else:
        with patch_context:
            repl.run()