def interact_ipython(header='', *args, **kwargs): global interact_ipython_ def pre_prompt_hook(_): R.gInterpreter.EndOfLineAction() # Interact is a callable which starts an ipython shell if not interact_ipython_: interact_ipython_ = InteractiveShellEmbed(banner1=UP_LINE) # needed for graphics to work correctly interact_ipython_.set_hook('pre_prompt_hook', pre_prompt_hook) stack_depth = kwargs.pop("stack_depth", 0) + 2 kwargs["stack_depth"] = stack_depth interact_ipython_(header, *args, **kwargs)
def interact_ipython(header='', *args, **kwargs): global interact_ipython_ def pre_prompt_hook(_): R.gInterpreter.EndOfLineAction() # Interact is a callable which starts an ipython shell if not interact_ipython_: interact_ipython_ = InteractiveShellEmbed(banner1=UP_LINE) # needed for graphics to work correctly interact_ipython_.set_hook('pre_prompt_hook', pre_prompt_hook) stack_depth = kwargs.pop("stack_depth", 0) + 2 kwargs["stack_depth"] = stack_depth interact_ipython_(header, *args, **kwargs)
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()
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()
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()
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", )
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()