Example #1
0
def ishell(local_ns):
    """Embed an IPython shell handing it the local namespace from
    :var:`local_ns`.
    """
    banner = (
        "Welcome to the pystuck interactive shell.\nUse the 'modules' dictionary "
        "to access remote modules (like 'os', or '__main__')\nUse the `%show "
        "threads` magic to display all thread stack traces.\n"
    )
    try:
        from IPython.terminal.embed import InteractiveShellEmbed

        ipshell = InteractiveShellEmbed(banner1=banner)
        ipshell.register_magics(IntrospectMagics)
        ipshell(local_ns=local_ns)
    except ImportError:
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        try:
            from IPython.Shell import IPShellEmbed

            ipshell = IPShellEmbed(argv=[], user_ns=local_ns, banner1=banner)
            ipshell.register_magics(IntrospectMagics)
            ipshell()
        except ImportError:
            # IPython not found at all, raise ImportError
            raise
Example #2
0
def ishell(local_ns):
    """Embed an IPython shell handing it the local namespace from
    :var:`local_ns`.
    """
    banner = (
        "Welcome to the pystuck interactive shell.\nUse the 'modules' dictionary "
        "to access remote modules (like 'os', or '__main__')\nUse the `%show "
        "threads` magic to display all thread stack traces.\n")
    try:
        from IPython.terminal.embed import InteractiveShellEmbed
        ipshell = InteractiveShellEmbed(banner1=banner)
        ipshell.register_magics(IntrospectMagics)
        ipshell(local_ns=local_ns)
    except ImportError:
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        try:
            from IPython.Shell import IPShellEmbed
            ipshell = IPShellEmbed(argv=[], user_ns=local_ns, banner1=banner)
            ipshell.register_magics(IntrospectMagics)
            ipshell()
        except ImportError:
            # IPython not found at all, raise ImportError
            raise
async def start_interactive_python(plugin, registry, ctx, args):
    await try_await(ctx.on_interactive(args))
    cmds = list(registry.get_all_commands())
    for cmd in cmds:
        # TODO: This currently works for AutoCommands only, it's a hack to get
        # the command as a function, clean this up and make
        # _get_executable_function a public member.
        if hasattr(cmd, "_get_executable_function"):
            executable = cmd._get_executable_function()
            names = cmd.get_command_names()
            for name in names:
                # function names cannot have - in them
                name = name.replace("-", "_")
                custom_locals[name] = executable

    cfg = Config()
    cfg.TerminalInteractiveShell.prompts_class = NubiaPrompt
    # Custom Config
    cfg.InteractiveShellEmbed.autocall = 2
    cfg.InteractiveShellEmbed.autoawait = True

    banner = "LogDevice IPython Shell;  Python {}".format(sys.version)
    ipkwargs = {
        "config": cfg,
        "banner1": banner,
        "banner2": "\n",
        "user_ns": custom_locals,
    }
    plugin.update_ipython_kwargs(ctx=ctx, kwargs=ipkwargs)

    ipshell = InteractiveShellEmbed(**ipkwargs)
    for magic in plugin.get_magics():
        ipshell.register_magics(magic)
    ipshell()
Example #4
0
def start_interactive_python(plugin, registry, ctx, args):
    ctx.on_interactive(args)
    cmds = list(registry.get_all_commands())
    for cmd in cmds:
        # TODO: This currently works for AutoCommands only, it's a hack to get
        # the command as a function, clean this up and make
        # _get_executable_function a public member.
        if hasattr(cmd, "_get_executable_function"):
            executable = cmd._get_executable_function()
            names = cmd.get_command_names()
            for name in names:
                # function names cannot have - in them
                name = name.replace("-", "_")
                custom_locals[name] = executable
    if ctx.target:
        header = "Connected to {}".format(colored(ctx.target, "green"))
        custom_locals["tier"] = ctx.tier_ops
    else:
        header = "Not connected to any tiers!"

    cfg = Config()
    cfg.TerminalInteractiveShell.prompts_class = CustomPrompt
    # Custom Config
    cfg.InteractiveShellEmbed.autocall = 2
    cfg.InteractiveShellEmbed.autoawait = True

    banner = "LogDevice IPython Shell;  Python {}".format(sys.version)

    ipshell = InteractiveShellEmbed(
        config=cfg,
        banner1=banner,
        banner2="\n",
        header=header,
        user_ns=custom_locals,
    )
    for magic in plugin.get_magics():
        ipshell.register_magics(magic)
    ipshell()
Example #5
0
def launch_ipython(banner, namespace, magic=None, *args, **kwargs):
    '''
    Invoke the ipython Read Evaluate Print Loop

    Args:
        banner (str): Display banner
        namespace (dict): Namespace to use
    '''

    from IPython.terminal.prompts import Prompts, Token
    from IPython.terminal.embed import InteractiveShellEmbed
    from traitlets.config.loader import Config

    class KatsPrompt(Prompts):
        '''
        Custom ipython prompt class
        '''
        def in_prompt_tokens(self, cli=None):
            _ = cli
            import kats
            return [(Token, kats.__name__), (Token.Prompt, ' > ')]

        def out_prompt_tokens(self):
            return [(Token, '    '), (Token.Prompt, ' < ')]

    cfg = Config()
    cfg.TerminalInteractiveShell.prompts_class = KatsPrompt

    shell = InteractiveShellEmbed(header='',
                                  banner1=banner,
                                  exit_msg='See you again!!!',
                                  config=cfg,
                                  user_ns=namespace)
    if magic:
        shell.register_magics(magic(shell, *args, **kwargs))

    shell()
Example #6
0
File: preg.py Project: iwm911/plaso
def RunModeConsole(front_end, options):
  """Open up an iPython console.

  Args:
    options: the command line arguments (instance of argparse.Namespace).
  """
  namespace = {}
  hives, hive_collectors = front_end.GetHivesAndCollectors(options)

  function_name_length = 23
  banners = []
  banners.append(frontend_utils.FormatHeader(
      'Welcome to PREG - home of the Plaso Windows Registry Parsing.'))
  banners.append('')
  banners.append('Some of the commands that are available for use are:')
  banners.append('')
  banners.append(frontend_utils.FormatOutputString(
      'cd key', 'Navigate the Registry like a directory structure.',
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      'ls [-v]', (
          'List all subkeys and values of a Registry key. If called as '
          'ls True then values of keys will be included in the output.'),
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      'parse -[v]', 'Parse the current key using all plugins.',
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      'pwd', 'Print the working "directory" or the path of the current key.',
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      'plugin [-h] plugin_name', (
          'Run a particular key-based plugin on the loaded hive. The correct '
          'Registry key will be loaded, opened and then parsed.'),
      function_name_length))

  banners.append('')

  if len(hives) == 1:
    hive = hives[0]
    hives = []
  else:
    hive = None

  if len(hive_collectors) == 1:
    hive_collector = hive_collectors[0][1]
    hive_collectors = []
  else:
    hive_collector = None

  if hive and not hive_collectors:
    OpenHive(hive, hive_collector)

  if RegCache.hive and RegCache.GetHiveName() != 'N/A':
    banners.append(
        u'Registry hive: {0:s} is available and loaded.'.format(
            RegCache.GetHiveName()))
  elif hives:
    banners.append('More than one Registry file ready for use.')
    banners.append('')
    banners.append('Registry files discovered:')
    for number, hive in enumerate(hives):
      banners.append(' - {0:d}  {1:s}'.format(number, hive.location))
    banners.append('')
    banners.append('To load a hive use:')
    text = 'OpenHive(hives[NR], collector)'

    if hive_collectors:
      banners.append('')
      banners.append((
          'There is more than one collector available. To use any of them '
          'instead of the attribute "collector" in the OpenHive '
          'function use the collectors attribute.\nThe available collectors '
          'are:'))
      counter = 0
      for name, _ in hive_collectors:
        if not name:
          name = 'Current Value'
        banners.append(' {0:d} = {1:s}'.format(counter, name))
        counter += 1

      banners.append(
          'To use the collector use:\ncollector = collectors[NR][1]\nwhere '
          'NR is the number as listed above.')
    else:
      banners.append(frontend_utils.FormatOutputString(text, (
          'Collector is an available attribute and NR is a number ranging'
          ' from 0 to {0:d} (see above which files these numbers belong to).'
          ' To get the name of the loaded hive use RegCache.GetHiveName()'
          ' and RegCache.hive_type to get the '
          'type.').format(len(hives) + 1), len(text)))
  else:
    # We have a single hive but many collectors.
    banners.append(
        'There is more than one collector available for the hive that was '
        'discovered. To open up a hive use:\nOpenHive(hive, collectors[NR][1])'
        '\nWhere NR is one of the following values:')

    counter = 0
    for name, _ in hive_collectors:
      if not name:
        name = 'Current Value'
      banners.append(' {0:d} = {1:s}'.format(counter, name))
      counter += 1

  banners.append('')
  banners.append('Happy command line console fu-ing.')

  # Adding variables in scope.
  namespace.update(globals())
  namespace.update({
      'hives': hives,
      'hive': hive,
      'collector': hive_collector,
      'collectors': hive_collectors})

  # Starting the shell.
  ipshell = InteractiveShellEmbed(
      user_ns=namespace, banner1=u'\n'.join(banners), exit_msg='')
  ipshell.confirm_exit = False
  # Adding "magic" functions.
  ipshell.register_magics(MyMagics)
  # Registering command completion for the magic commands.
  ipshell.set_hook('complete_command', CdCompleter, str_key='%cd')
  ipshell.set_hook('complete_command', VerboseCompleter, str_key='%ls')
  ipshell.set_hook('complete_command', VerboseCompleter, str_key='%parse')
  ipshell.set_hook('complete_command', PluginCompleter, str_key='%plugin')
  ipshell()
Example #7
0
"""\
                                               __
    .---.-.-----.--.--.---.-.----.-----.-----.|  |
    |  _  |  _  |  |  |  _  |   _|  -__|  _  ||  |
    |___._|__   |_____|___._|__| |_____|   __||__|
             |__|                      |__|

    ----a repl for the aqua hplc controller------
"""

from .magics import Magics

from IPython.terminal.embed import InteractiveShellEmbed

ipy = InteractiveShellEmbed()

ipy.register_magics(Magics)


def run():
    ipy.show_banner(__doc__)
    ipy.mainloop()
Example #8
0
You can script the device's SCSI interface too:

    sc c ac              # Backdoor signature
    sc 8 ff 00 ff        # Undocumented firmware version
    ALSO: reset, eject, sc_sense, sc_read, scsi_in, scsi_out

Happy hacking!    -- Type 'thing?' for help on 'thing' or
~MeS`14              '?' for IPython, '%h' for this again.
"""

from IPython.terminal.embed import InteractiveShellEmbed
from shell_magics import ShellMagics
from remote import Device
import shell_namespace

# Make a global device, but only give it to the user namespace.
# Make it default by assigning it to 'd', our current device.
shell_namespace.d = shell_namespace.d_remote = Device()

# Make a shell that feels like a debugger
ipy = InteractiveShellEmbed(user_ns = shell_namespace.__dict__)
shell_namespace.ipy = ipy
ipy.register_magics(ShellMagics)
ipy.register_magic_function(lambda _: ipy.write(__doc__), magic_name='h')
ipy.alias_manager.define_alias('git', 'git')
ipy.alias_manager.define_alias('make', 'make')

# Hello, tiny world
ipy.mainloop(display_banner = __doc__)
Example #9
0
cfg.PromptManager.out_template = r'<\#> '

# Whether to display a banner upon starting IPython.
cfg.TerminalIPythonApp.display_banner = True

# Set the editor used by IPython (default to $EDITOR/vi/notepad).
cfg.TerminalInteractiveShell.editor = 'emacs -nw'

# The part of the banner to be printed before the profile
cfg.TerminalInteractiveShell.banner1 = swarm_shell_banner

# The part of the banner to be printed after the profile
cfg.TerminalInteractiveShell.banner2 = ''

# Set to confirm when you try to exit IPython with an EOF 
cfg.TerminalInteractiveShell.confirm_exit = False

# Setup logging
logging.basicConfig()
logging.getLogger('katcp').setLevel(logging.CRITICAL)
logging.getLogger('').setLevel(logging.INFO)

# Set up SWARM 
swarm = Swarm()

# Start the IPython embedded shell
ipshell = InteractiveShellEmbed(config=cfg)
swarm_shell_magics = magics.SwarmShellMagics(ipshell, swarm)
ipshell.register_magics(swarm_shell_magics)
ipshell()
Example #10
0
from shell_magics import ShellMagics
from remote import Device
import shell_namespace
import sys

messages = ''
user_ns = dict(shell_namespace.__dict__)

# Make a global device, but only give it to the user namespace.
# Make it default by assigning it to 'd', our current device.
try:
    user_ns['d'] = user_ns['d_remote'] = Device()
except IOError as e:
    messages += "\n-------- There is NO DEVICE available! --------\n"
    messages += "\n%s\n\n" % e
    messages += "--> Try again to attach via USB:   %reset\n"
    messages += "--> Reattach over bitbang serial:  %bitbang -a /dev/tty.usb<tab>\n"
    user_ns['d'] = user_ns['d_remote'] = None

# Make a shell that feels like a debugger
ipy = InteractiveShellEmbed(user_ns=user_ns)
user_ns['ipy'] = ipy
ipy.register_magics(ShellMagics)
ipy.register_magic_function(lambda _: ipy.write(__doc__), magic_name='h')
ipy.alias_manager.define_alias('git', 'git')
ipy.alias_manager.define_alias('make', 'make')

# Hello, tiny world
sys.stdout.write(__doc__ + messages)
ipy.mainloop()
Example #11
0
    def Run(self):
        """Runs the interactive console."""
        source_type = self.preg_tool.source_type
        if source_type == dfvfs_definitions.SOURCE_TYPE_FILE:
            registry_file_types = []
        elif self.preg_tool.registry_file:
            registry_file_types = [self.preg_tool.registry_file]
        else:
            # No Registry type specified use all available types instead.
            registry_file_types = self.preg_tool.GetRegistryTypes()

        registry_helpers = self.preg_tool.GetRegistryHelpers(
            self.preg_tool.artifacts_registry,
            plugin_names=self.preg_tool.plugin_names,
            registry_file_types=registry_file_types)

        for registry_helper in registry_helpers:
            self.AddRegistryHelper(registry_helper)

        # Adding variables in scope.
        namespace = {}

        namespace.update(globals())
        namespace.update({
            'console': self,
            'get_current_key': self._CommandGetCurrentKey,
            'get_key': self._CommandGetCurrentKey,
            'get_value': self._CommandGetValue,
            'get_value_data': self._CommandGetValueData,
            'tool': self.preg_tool
        })

        ipshell_config = self.GetConfig()

        if len(self._registry_helpers) == 1:
            self.LoadRegistryFile(0)

        registry_helper = self._currently_registry_helper

        if registry_helper:
            registry_file_path = registry_helper.name
        else:
            registry_file_path = 'NO HIVE LOADED'

        self.SetPrompt(registry_file_path=registry_file_path,
                       configuration=ipshell_config)

        # Starting the shell.
        ipshell = InteractiveShellEmbed(user_ns=namespace,
                                        config=ipshell_config,
                                        banner1='',
                                        exit_msg='')
        ipshell.confirm_exit = False

        self.PrintBanner()

        # Adding "magic" functions.
        ipshell.register_magics(PregMagics)
        PregMagics.console = self

        # Set autocall to two, making parenthesis not necessary when calling
        # function names (although they can be used and are necessary sometimes,
        # like in variable assignments, etc).
        ipshell.autocall = 2

        # Registering command completion for the magic commands.
        ipshell.set_hook('complete_command', CommandCompleterCd, str_key='%cd')
        ipshell.set_hook('complete_command',
                         CommandCompleterVerbose,
                         str_key='%ls')
        ipshell.set_hook('complete_command',
                         CommandCompleterVerbose,
                         str_key='%parse')
        ipshell.set_hook('complete_command',
                         CommandCompleterPlugins,
                         str_key='%plugin')

        ipshell()
Example #12
0
def RunModeConsole(front_end, options):
  """Open up an iPython console.

  Args:
    options: the command line arguments (instance of argparse.Namespace).
  """
  namespace = {}

  function_name_length = 23
  banners = []
  banners.append(frontend_utils.FormatHeader(
      u'Welcome to PREG - home of the Plaso Windows Registry Parsing.'))
  banners.append(u'')
  banners.append(u'Some of the commands that are available for use are:')
  banners.append(u'')
  banners.append(frontend_utils.FormatOutputString(
      u'cd key', u'Navigate the Registry like a directory structure.',
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      u'ls [-v]', (
          u'List all subkeys and values of a Registry key. If called as '
          u'ls True then values of keys will be included in the output.'),
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      u'parse -[v]', u'Parse the current key using all plugins.',
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      u'pwd', u'Print the working "directory" or the path of the current key.',
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      u'plugin [-h] plugin_name', (
          u'Run a particular key-based plugin on the loaded hive. The correct '
          u'Registry key will be loaded, opened and then parsed.'),
      function_name_length))
  banners.append(frontend_utils.FormatOutputString(
      u'get_value value_name', (
          u'Get a value from the currently loaded Registry key.')))
  banners.append(frontend_utils.FormatOutputString(
      u'get_value_data value_name', (
          u'Get a value data from a value stored in the currently loaded '
          u'Registry key.')))
  banners.append(frontend_utils.FormatOutputString(
      u'get_key', u'Return the currently loaded Registry key.'))

  banners.append(u'')

  # Build the global cache and prepare the tool.
  hive_storage = preg.PregStorage()
  shell_helper = preg.PregHelper(options, front_end, hive_storage)
  parser_mediator = shell_helper.BuildParserMediator()

  preg.PregCache.parser_mediator = parser_mediator
  preg.PregCache.shell_helper = shell_helper
  preg.PregCache.hive_storage = hive_storage

  registry_types = getattr(options, 'regfile', None)
  if isinstance(registry_types, basestring):
    registry_types = registry_types.split(u',')

  if not registry_types:
    registry_types = [
        'NTUSER', 'USRCLASS', 'SOFTWARE', 'SYSTEM', 'SAM', 'SECURITY']
  preg.PregCache.shell_helper.Scan(registry_types)

  if len(preg.PregCache.hive_storage) == 1:
    preg.PregCache.hive_storage.SetOpenHive(0)
    hive_helper = preg.PregCache.hive_storage.loaded_hive
    banners.append(
        u'Opening hive: {0:s} [{1:s}]'.format(
            hive_helper.path, hive_helper.collector_name))
    ConsoleConfig.SetPrompt(hive_path=hive_helper.path)

  loaded_hive = preg.PregCache.hive_storage.loaded_hive

  if loaded_hive and loaded_hive.name != u'N/A':
    banners.append(
        u'Registry hive: {0:s} is available and loaded.'.format(
            loaded_hive.name))
  else:
    banners.append(u'More than one Registry file ready for use.')
    banners.append(u'')
    banners.append(preg.PregCache.hive_storage.ListHives())
    banners.append(u'')
    banners.append((
        u'Use "hive open INDEX" to load a hive and "hive list" to see a '
        u'list of available hives.'))

  banners.append(u'')
  banners.append(u'Happy command line console fu-ing.')

  # Adding variables in scope.
  namespace.update(globals())
  namespace.update({
      'get_current_key': GetCurrentKey,
      'get_key': GetCurrentKey,
      'get_value': GetValue,
      'get_value_data': GetValueData,
      'number_of_hives': GetTotalNumberOfLoadedHives,
      'range_of_hives': GetRangeForAllLoadedHives,
      'options': options})

  ipshell_config = ConsoleConfig.GetConfig()

  if loaded_hive:
    ConsoleConfig.SetPrompt(
        hive_path=loaded_hive.name, config=ipshell_config)
  else:
    ConsoleConfig.SetPrompt(hive_path=u'NO HIVE LOADED', config=ipshell_config)

  # Starting the shell.
  ipshell = InteractiveShellEmbed(
      user_ns=namespace, config=ipshell_config, banner1=u'\n'.join(banners),
      exit_msg='')
  ipshell.confirm_exit = False
  # Adding "magic" functions.
  ipshell.register_magics(MyMagics)
  # Set autocall to two, making parenthesis not necessary when calling
  # function names (although they can be used and are necessary sometimes,
  # like in variable assignments, etc).
  ipshell.autocall = 2
  # Registering command completion for the magic commands.
  ipshell.set_hook('complete_command', CdCompleter, str_key='%cd')
  ipshell.set_hook('complete_command', VerboseCompleter, str_key='%ls')
  ipshell.set_hook('complete_command', VerboseCompleter, str_key='%parse')
  ipshell.set_hook('complete_command', PluginCompleter, str_key='%plugin')

  ipshell()
Example #13
0
def main():
    my_parser = argparse.ArgumentParser()
    my_parser.add_argument("-q",
                           dest="quiet",
                           default=False,
                           action="store_true",
                           help="be quiet [%(default)s]")
    my_parser.add_argument("--logger",
                           type=str,
                           default="stdout",
                           choices=["stdout", "logserver"],
                           help="choose logging facility [%(default)s]")
    my_parser.add_argument(
        "--logall",
        default=False,
        action="store_true",
        help="log all (no just warning / error), [%(default)s]")
    my_parser.add_argument("args",
                           nargs=argparse.REMAINDER,
                           help="commands to execute")
    opts = my_parser.parse_args()
    if opts.args:
        opts.quiet = True
    if not opts.quiet:
        print("Starting ICSW shell ... ", end="", flush=True)

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "initat.cluster.settings")

    try:
        import django
        if not opts.quiet:
            print("django.setup() ... ", end="", flush=True)
        django.setup()
    except:
        django = None
    else:
        from initat.cluster.backbone import db_tools
        try:
            if not db_tools.is_reachable():
                django = None
        except:
            # when installing a newer icsw-client package on a machine with an old icsw-server package
            django = None

    from initat.icsw.magics import icsw_magics

    # First import the embeddable shell class
    from IPython.terminal.prompts import Prompts, Token
    from IPython.terminal.embed import InteractiveShellEmbed

    # Now create an instance of the embeddable shell. The first argument is a
    # string with options exactly as you would type them if you were starting
    # IPython at the system command line. Any parameters you want to define for
    # configuration can thus be specified here.
    ipshell = InteractiveShellEmbed(header="X", user_ns={"django": django})

    class ICSWPrompt(Prompts):
        def in_prompt_tokens(self, cli=None):
            return [
                (Token, "[CORVUS]"),
                (Token.Prompt, ">"),
            ]

    ipshell.prompts = ICSWPrompt(ipshell)

    ipshell.mouse_support = True
    ipshell.confirm_exit = False
    ipshell.autocall = 2
    # no banner
    ipshell.banner1 = ""
    ipshell.set_hook('complete_command',
                     icsw_magics.apt_completers,
                     str_key='icsw')

    if False:

        class st2(object):
            def __dir__(self):
                return ["bla", "blo"]

            def abc(self, var):
                print("*", var)

            def _ipython_key_completions_(self):
                return ["x", "y"]

            def bla(self):
                return "bla"

            def __call__(self, *args):
                return "C", args

        xicsw = st2()

        def stest(sthg):
            print("stest:", sthg)

    ipshell.register_magics(
        icsw_magics.ICSWMagics(ipshell, True if django else False))

    if opts.args:
        if "--" in opts.args:
            opts.args.remove("--")
        _args = ["icsw"]
        if opts.logall:
            _args.append("--logall")
        _args.append("--logger")
        _args.append(opts.logger)
        r = ipshell.run_cell(" ".join(_args + opts.args), silent=True)
        sys.exit(r.result)
    else:
        if not opts.quiet:
            print("done")
        from initat.cluster.backbone.models import device, device_group
        ipshell(header="Starting icsw", )
Example #14
0
    def cmagic(self, line, cell):
        "my cell magic"
        return line, cell

    @line_cell_magic
    def lcmagic(self, line, cell=None):
        "Magic that works both as %lcmagic and as %%lcmagic"
        if cell is None:
            print("Called as line magic")
            return line
        else:
            print("Called as cell magic")
            return line, cell


ipyshell.register_magics(MyMagics)

# Goal: execute this after the IPython shell starts, embedded in the local namespace (so ctx (see below) is in locals()"
#START = '''
#@register_line_magic
#def click_invoke(ctx, f, *args, **kwargs):
#    return ctx.invoke(f, *args, **kwargs)
#'''


@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):

    ipyshell()
Example #15
0
File: preg.py Project: f-s-p/plaso
def RunModeConsole(front_end, options):
    """Open up an iPython console.

  Args:
    options: the command line arguments (instance of argparse.Namespace).
  """
    namespace = {}

    function_name_length = 23
    banners = []
    banners.append(
        frontend_utils.FormatHeader(
            u'Welcome to PREG - home of the Plaso Windows Registry Parsing.'))
    banners.append(u'')
    banners.append(u'Some of the commands that are available for use are:')
    banners.append(u'')
    banners.append(
        frontend_utils.FormatOutputString(
            u'cd key', u'Navigate the Registry like a directory structure.',
            function_name_length))
    banners.append(
        frontend_utils.FormatOutputString(
            u'ls [-v]',
            (u'List all subkeys and values of a Registry key. If called as '
             u'ls True then values of keys will be included in the output.'),
            function_name_length))
    banners.append(
        frontend_utils.FormatOutputString(
            u'parse -[v]', u'Parse the current key using all plugins.',
            function_name_length))
    banners.append(
        frontend_utils.FormatOutputString(
            u'pwd',
            u'Print the working "directory" or the path of the current key.',
            function_name_length))
    banners.append(
        frontend_utils.FormatOutputString(u'plugin [-h] plugin_name', (
            u'Run a particular key-based plugin on the loaded hive. The correct '
            u'Registry key will be loaded, opened and then parsed.'),
                                          function_name_length))
    banners.append(
        frontend_utils.FormatOutputString(
            u'get_value value_name',
            (u'Get a value from the currently loaded Registry key.')))
    banners.append(
        frontend_utils.FormatOutputString(
            u'get_value_data value_name',
            (u'Get a value data from a value stored in the currently loaded '
             u'Registry key.')))
    banners.append(
        frontend_utils.FormatOutputString(
            u'get_key', u'Return the currently loaded Registry key.'))

    banners.append(u'')

    # Build the global cache and prepare the tool.
    hive_storage = preg.PregStorage()
    shell_helper = preg.PregHelper(options, front_end, hive_storage)
    parser_mediator = shell_helper.BuildParserMediator()

    preg.PregCache.parser_mediator = parser_mediator
    preg.PregCache.shell_helper = shell_helper
    preg.PregCache.hive_storage = hive_storage

    registry_types = getattr(options, 'regfile', None)
    if isinstance(registry_types, basestring):
        registry_types = registry_types.split(u',')

    if not registry_types:
        registry_types = [
            'NTUSER', 'USRCLASS', 'SOFTWARE', 'SYSTEM', 'SAM', 'SECURITY'
        ]
    preg.PregCache.shell_helper.Scan(registry_types)

    if len(preg.PregCache.hive_storage) == 1:
        preg.PregCache.hive_storage.SetOpenHive(0)
        hive_helper = preg.PregCache.hive_storage.loaded_hive
        banners.append(u'Opening hive: {0:s} [{1:s}]'.format(
            hive_helper.path, hive_helper.collector_name))
        ConsoleConfig.SetPrompt(hive_path=hive_helper.path)

    loaded_hive = preg.PregCache.hive_storage.loaded_hive

    if loaded_hive and loaded_hive.name != u'N/A':
        banners.append(u'Registry hive: {0:s} is available and loaded.'.format(
            loaded_hive.name))
    else:
        banners.append(u'More than one Registry file ready for use.')
        banners.append(u'')
        banners.append(preg.PregCache.hive_storage.ListHives())
        banners.append(u'')
        banners.append(
            (u'Use "hive open INDEX" to load a hive and "hive list" to see a '
             u'list of available hives.'))

    banners.append(u'')
    banners.append(u'Happy command line console fu-ing.')

    # Adding variables in scope.
    namespace.update(globals())
    namespace.update({
        'get_current_key': GetCurrentKey,
        'get_key': GetCurrentKey,
        'get_value': GetValue,
        'get_value_data': GetValueData,
        'number_of_hives': GetTotalNumberOfLoadedHives,
        'range_of_hives': GetRangeForAllLoadedHives,
        'options': options
    })

    ipshell_config = ConsoleConfig.GetConfig()

    if loaded_hive:
        ConsoleConfig.SetPrompt(hive_path=loaded_hive.name,
                                config=ipshell_config)
    else:
        ConsoleConfig.SetPrompt(hive_path=u'NO HIVE LOADED',
                                config=ipshell_config)

    # Starting the shell.
    ipshell = InteractiveShellEmbed(user_ns=namespace,
                                    config=ipshell_config,
                                    banner1=u'\n'.join(banners),
                                    exit_msg='')
    ipshell.confirm_exit = False
    # Adding "magic" functions.
    ipshell.register_magics(MyMagics)
    # Set autocall to two, making parenthesis not necessary when calling
    # function names (although they can be used and are necessary sometimes,
    # like in variable assignments, etc).
    ipshell.autocall = 2
    # Registering command completion for the magic commands.
    ipshell.set_hook('complete_command', CdCompleter, str_key='%cd')
    ipshell.set_hook('complete_command', VerboseCompleter, str_key='%ls')
    ipshell.set_hook('complete_command', VerboseCompleter, str_key='%parse')
    ipshell.set_hook('complete_command', PluginCompleter, str_key='%plugin')

    ipshell()