Ejemplo n.º 1
0
    def handle(self, **options):
        imported_objects = {}
        try:
            from django.db.models.loading import get_models
        except ImportError:
            from django.apps import apps
            get_models = apps.get_models
        for m in get_models():
            imported_objects[m.__name__] = m

        try:
            self.ipython(imported_objects)
        except ImportError:
            import code
            try:  # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try'
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(
                    rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")
            code.interact(local=imported_objects)
Ejemplo n.º 2
0
    def main_loop(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.rl_completer_safe)
        #print 'delims: ', repr(readline.get_completer_delims())

        hist_file = os.path.expanduser("~/.qadmin_history")
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

        print "Use 'show help;' to see available commands."
        while 1:
            try:
                ln = self.line_input()
                self.exec_string(ln)
            except KeyboardInterrupt:
                print
            except EOFError:
                print
                break
            self.reset_comp_cache()

        try:
            readline.write_history_file(hist_file)
        except IOError:
            pass
Ejemplo n.º 3
0
        def run_plain():
            # Using normal Python shell
            import code
            imported_objects = import_objects(options, self.style)
            try:
                # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
            # conventions and get $PYTHONSTARTUP first then import user.
            if use_pythonrc:
                pythonrc = os.environ.get("PYTHONSTARTUP")
                if pythonrc and os.path.isfile(pythonrc):
                    global_ns = {}
                    with open(pythonrc) as rcfile:
                        try:
                            six.exec_(compile(rcfile.read(), pythonrc, 'exec'), global_ns)
                            imported_objects.update(global_ns)
                        except NameError:
                            pass
                # This will import .pythonrc.py as a side-effect
                try:
                    import user  # NOQA
                except ImportError:
                    pass
            code.interact(local=imported_objects)
def sshcheck():
  attacks = {}
  users = {}
  try:
    import readline, rlcompleter
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(complete)
  except ImportError:
    print 'No Tab Completion'
  LOGs = raw_input('Enter the path to the log file: ')
  for LOG in LOGs.split(' '):
    if LOG.endswith('.gz'):
      auth_logs = gzip.GzipFile(LOG, 'r')
    else:
      auth_logs = open(LOG, 'r')
    if len(LOGs) is '1':
      print "Parsing log file"
    else:
      print "Parsing log files"
    for log in auth_logs:
      l = {"raw": log }
      normalizer.normalize(l)
      if l.get('action') == 'fail' and l.get('program') == 'sshd':
        u = l['user']
        p = l['source_ip']
        o1, o2, o3, o4 = [int(i) for i in p.split('.')]
        if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10:
          print "Private IP, %s No geolocation data" %str(p)
        attacks[p] = attacks.get(p, 0) + 1
  getip()
  dojson(attacks, IP)
Ejemplo n.º 5
0
    def register_readline():
        import atexit
        try:
            import readline
            import rlcompleter
        except ImportError:
            return

        # Reading the initialization (config) file may not be enough to set a
        # completion key, so we set one first and then read the file
        if 'libedit' in getattr(readline, '__doc__', ''):
            readline.parse_and_bind('bind ^I rl_complete')
        else:
            readline.parse_and_bind('tab: complete')

        try:
            readline.read_init_file()
        except OSError:
            # An OSError here could have many causes, but the most likely one
            # is that there's no .inputrc file (or .editrc file in the case of
            # Mac OS X + libedit) in the expected location.  In that case, we
            # want to ignore the exception.
            pass

        history = os.path.join(os.path.expanduser('~'), '.python_history')
        try:
            readline.read_history_file(history)
        except IOError:
            pass
        atexit.register(readline.write_history_file, history)
Ejemplo n.º 6
0
    def cmdloop(self, intro=None):
        self.old_completer = readline.get_completer()
        self.old_completer_delims = readline.get_completer_delims()
        readline.set_completer(self.complete)
        readline.parse_and_bind(self.completekey+": complete")
        readline.parse_and_bind("set bell-style none")
        readline.parse_and_bind("set show-all-if-ambiguous")
        readline.parse_and_bind("set completion-query-items -1")

        # If press help key, add the character and accept the line
        readline.parse_and_bind('"?": "\C-q?\C-j"')
        # Register a function for execute before read user
        # input. We can use it for insert text at command line
        readline.set_pre_input_hook(self.pre_input_hook)
        readline.set_completer_delims(' \t\n')

        try:
            stop = None
            while not stop:
                try:
                    line = raw_input(self.prompt)
                except EOFError:
                    line = 'EOF'

                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
        finally:
            readline.set_completer(self.old_completer)
            readline.set_completer_delims(self.old_completer_delims)
Ejemplo n.º 7
0
def run_classic_shell(locals, globals, first_time):
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
    else:
        banner = ""

    ns = SetPropagatingDict([locals, globals], locals)

    from pudb.settings import get_save_config_path
    from os.path import join
    hist_file = join(
            get_save_config_path(),
            "shell-history")

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)

    cons.interact(banner)

    if HAVE_READLINE:
        readline.write_history_file(hist_file)
Ejemplo n.º 8
0
    def run_shell(self):
        do_readline = sys.stdin.isatty() and ('-', sys.stdin) in self.files
        if do_readline and os.path.exists(os.path.expanduser('~/.fsh_history')):
            readline.read_history_file(os.path.expanduser('~/.fsh_history'))
            for file in ('/etc/inputrc', os.path.expanduser('~/.inputrc')):
                if os.path.exists(file):
                    with open(file) as fd:
                        readline.parse_and_bind(fd.read())

        while self.files:
            self.curfile, self.curfd, self.curline = self.files[0]
            self.files = self.files[1:]
            if self.verbose:
                print "%s(Now processing %s)" % (self.ps4, self.curfile)
            try:
                while True:
                    line = self.get_input()
                    if not line:
                        break
                    if self.verbose:
                        print '%s%s (%s, line %d)' % (self.ps4, line, self.curfile, self.curline)
                    self.parse_and_run(line)

            except:
                if do_readline:
                    readline.write_history_file(os.path.expanduser('~/.fsh_history'))
                raise

        if do_readline:
            readline.write_history_file(os.path.expanduser('~/.fsh_history'))
Ejemplo n.º 9
0
 def init_readline(self):
     init_file = os.path.expanduser("~/.%s-init" % self.__name)
     readline.parse_and_bind("set bell-style visible")
     try:
         readline.read_init_file(init_file)
     except IOError:
         pass
Ejemplo n.º 10
0
 def cmd_debug(self, argv, help):
     """Prints some debug info for this script"""
     parser = argparse.ArgumentParser(
         prog="aws debug",
         description=help,
     )
     instances = self.get_instances(command='startup_script')
     parser.add_argument("server", nargs=1,
                         metavar="instance",
                         help="Name of the instance from the config.",
                         choices=list(instances))
     parser.add_argument("-v", "--verbose", dest="verbose",
                       action="store_true", help="Print more info")
     parser.add_argument("-i", "--interactive", dest="interactive",
                       action="store_true", help="Creates a connection and drops you into pdb")
     parser.add_argument("-o", "--override", nargs="*", type=str,
                         dest="overrides", metavar="OVERRIDE",
                         help="Option to override server config for startup script (name=value).")
     args = parser.parse_args(argv)
     overrides = self._parse_overrides(args)
     overrides['servers'] = self.instances
     server = instances[args.server[0]]
     startup_script = server.startup_script(overrides=overrides, debug=True)
     max_size = getattr(server, 'max_startup_script_size', 16 * 1024)
     log.info("Length of startup script: %s/%s", len(startup_script), max_size)
     if args.verbose:
         log.info("Startup script:")
         print startup_script,
     if args.interactive:  # pragma: no cover
         import readline
         conn = server.conn
         instance = server.instance
         conn, instance  # shutup pyflakes
         readline.parse_and_bind('tab: complete')
         __import__("code").interact(local=locals())
Ejemplo n.º 11
0
def main():
    """Main function."""
    # Enable tab completion
    readline.parse_and_bind('tab: complete')

    # Set prompt
    sys.ps1 = colorize_prompt('>>> ', 'blue', 'bold')
    sys.ps2 = colorize_prompt('... ', 'yellow', 'bold')

    # Constrict history size
    readline.set_history_length(HISTSIZE)

    # Create custom history file
    touch(CUSTOM_HISTFILE)

    # Load custom history file
    load_history(CUSTOM_HISTFILE)

    # Use custom history file
    atexit.register(readline.write_history_file, CUSTOM_HISTFILE)

    # Remove default history at exit
    atexit.register(remove_file, DEFAULT_HISTFILE)

    # Use pprint to print variables
    sys.displayhook = displayhook_pprint
Ejemplo n.º 12
0
    def __init__(self):
        self.sentCache = {}
        self.commands = {}
        self.acceptingInput = False
        self.lastPrompt = True

        self._queuedCmds = []

        readline.set_completer(self.complete)
        readline.parse_and_bind('tab: complete')

        members = inspect.getmembers(self, predicate = inspect.ismethod)
        for m in members:
            if hasattr(m[1], "clidesc"):
                fname = m[0]
                fn = m[1]
                try:
                    cmd, subcommand = fname.split('_')
                except ValueError:
                    cmd = fname
                    subcommand = "_"


                if not cmd in self.commands:
                    self.commands[cmd] = {}

                self.commands[cmd][subcommand] = {
                   "args": inspect.getargspec(fn)[0][1:],
                   "desc": fn.clidesc,
                   "fn": fn,
                   "order": fn.cliorder
                }
        self.cv = threading.Condition()
        self.inputThread = threading.Thread(target = self.startInputThread, args = (self.cv,))
        self.inputThread.daemon = True
Ejemplo n.º 13
0
def file_chooser(prompt_text = "Enter File: ", default=None, filearg=[], filekwarg={}):
    """A simple tool to get a file from the user. Takes keyworded arguemnts
    and passes them to open().
    
    If the user enters nothing the function will return the ``default`` value.
    Otherwise it continues to prompt the user until it get's a decent response.
    
    filekwarg may contain arguements passed on to ``open()``.
    """
    try:
        import readline, rlcomplete
        completer = rlcomplete.PathCompleter()
        readline.set_completer_delims(completer.delims)
        readline.parse_and_bind("tab: complete")
        readline.set_completer(completer.complete)
    except ImportError:
        pass
    while True:
        f = raw_input(prompt_text)
        if f == '': return default
        f = os.path.expanduser(f)
        if len(f) != 0 and f[0] == os.path.sep:
            f = os.path.abspath(f)
        try:
            return open(f, *filearg, **filekwarg)
        except IOError, e:
            stderr.write(ERROR_MESSAGE % ("unable to open %s : %s" % (f, e)))
Ejemplo n.º 14
0
    def __init__(self, inp=None, out=None, opts={}):
        get_option = lambda key: Mmisc.option_set(opts, key,
                                                  DEFAULT_USER_SETTINGS)

        Minput = import_relative('input', '..inout', 'trepan')
        Moutput = import_relative('output', '..inout', 'trepan')

        atexit.register(self.finalize)
        self.interactive = True  # Or at least so we think initially
        self.input       = inp or Minput.DebuggerUserInput()
        self.output      = out or Moutput.DebuggerUserOutput()

        if self.input.use_history():
            complete = get_option('complete')
            if complete:
                parse_and_bind("tab: complete")
                set_completer(complete)
                pass
            self.histfile = get_option('histfile')
            if self.histfile:
                try:
                    read_history_file(histfile)
                except IOError:
                    pass
                set_history_length(50)
                atexit.register(write_history_file, self.histfile)
                pass
        return
Ejemplo n.º 15
0
def interactive_browser(srcdir=None):
    """
    launch an interactive view for browsing the original
    archives.
    """

    info("launching interactive data browser...")

    # the variable is actually used, in the interactive prompt.
    # pylint: disable=unused-variable
    data, game_versions = mount_input(srcdir)

    if not data:
        warn("cannot launch browser as no valid input assets were found.")
        return

    def save(path, target):
        """
        save a path to a custom target
        """
        with path.open("rb") as infile:
            with open(target, "rb") as outfile:
                outfile.write(infile.read())

    def save_slp(path, target, palette=None):
        """
        save a slp as png.
        """
        from .texture import Texture
        from .slp import SLP
        from .driver import get_palette

        if not palette:
            palette = get_palette(data, game_versions)

        with path.open("rb") as slpfile:
            tex = Texture(SLP(slpfile.read()), palette)

            out_path, filename = os.path.split(target)
            tex.save(Directory(out_path).root, filename)

    import code
    from pprint import pprint

    import rlcompleter

    completer = rlcompleter.Completer(locals())
    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind("set show-all-if-ambiguous on")
    readline.set_completer(completer.complete)

    code.interact(
        banner=("\nuse `pprint` for beautiful output!\n"
                "you can access stuff by the `data` variable!\n"
                "`data` is an openage.util.fslike.path.Path!\n"
                "* list contents:      `pprint(list(data['graphics'].list()))`\n"
                "* dump data:          `save(data['file/path'], '/tmp/outputfile')`.\n"
                "* save a slp as png:  `save_slp(data['dir/123.slp'], '/tmp/pic.png')`.\n"),
        local=locals()
    )
Ejemplo n.º 16
0
def interact(PS1, PS2, BANNER, *arg, **kwarg):
	def Completer(text, stat):
		if text.startswith('.') or text.startswith('/'):
			ret = path_matches(text)
		elif '.' not in text:
			ret = global_matches(text)
		else:
			ret = attr_matches(text)

		try:
			return ret[stat]
		except IndexError:
			return None
	@utils.regExitCallback
	def exit_interact():
		""" Clean all when exit """
		
		print "Goodbye..."

	## Compatible for Mac OS since Mac OS ship libedit for readline
	if "libedit" in readline.__doc__:
		import rlcompleter
		readline.parse_and_bind("bind ^I rl_complete")
	else:
		readline.parse_and_bind("tab: complete")

	## Change PS
	sys.ps1, sys.ps2 = PS1, PS2
	delims = readline.get_completer_delims().replace('/','')
	readline.set_completer_delims(delims)
	readline.set_completer(Completer)


	## Run Interpreter
	code.interact(banner=BANNER, local=globals())
Ejemplo n.º 17
0
def main(argv):
  if len(argv) <= 1:
    client = SenseiClient()
  else:
    host = argv[1]
    port = int(argv[2])
    print "url specified, host: %s, port: %d" % (host,port)
    client = SenseiClient(host,port,'sensei')
  logger.setLevel(logging.DEBUG)
  formatter = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d - %(message)s")
  stream_handler = logging.StreamHandler()
  stream_handler.setFormatter(formatter)
  logger.addHandler(stream_handler)

  

  def test_sql(stmt):
    # test(stmt)
    req = SenseiRequest(stmt)
    res = client.doQuery(req)
    res.display(req.get_columns(), 1000)

  import readline
  readline.parse_and_bind("tab: complete")
  while 1:
    try:
      stmt = raw_input('> ')
      if stmt == "exit":
        break
      test_sql(stmt)
    except EOFError:
      print
      break
    except ParseException as err:
      print " "*err.loc + "^\n" + err.msg
Ejemplo n.º 18
0
def tupni(message, Filename): # Input backwards in case you were wondering
	
	# Function within a function... Not sure if its the right thing to do but ah well! This is the function that allows the autocomplete magic to happen
	def completer(text, state):
		options = [x for x in lowlist if x.startswith(text)]
		try:
			return options[state]
		except IndexError:
			return None

	readline.set_completer(completer)
	readline.parse_and_bind("tab: complete")

	# If a list is given it is changed to lowercase (this makes it easier to type and hold the book open at the same time). If the word is not on the specified list then it is added to the list and written to file
	if Filename:
		csvfile = Filename + ".csv"
		List = CSVToList(Filename)
		lowlist = [x.lower() for x in List]
		word = raw_input(message)
		
		if not (word in lowlist or word == ""):# Check if word is already on list and to stop blank input be written to the file
			writer = csv.writer(open(csvfile, 'a'), delimiter=',')
			fileline = [x.replace(" ","_") for x in [word.title()]]
			writer.writerow(fileline)
	else:
		word = raw_input(message)

	return word.title()
def main():
    parser = OptionParser(usage="%prog [options] nand_image.bin device_infos.plist")
    (options, args) = parser.parse_args()

    if sys.platform == "darwin":
        import readline
        import rlcompleter
        #fix tab complete on osx
        if readline.__doc__ and "libedit" in readline.__doc__:
            readline.parse_and_bind("bind ^I rl_complete")
        else:
            readline.parse_and_bind("tab: complete")

    if len(args) >= 2:
        plistname = args[1]
        nandimagename = args[0]
        device_infos = plistlib.readPlist(plistname)
        print "Loading device information from %s" % plistname
    else:
        nandimagename ="remote"
        client = RamdiskToolClient.get()
        device_infos = client.device_infos
    print_device_infos(device_infos)
    image = NAND(nandimagename, device_infos)

    ExaminerShell(image).cmdloop("")
Ejemplo n.º 20
0
def main(files=[]):
    printtty(colorize('> ', PROMPT_COLOR) + "; Type HELP to get the HELP")
    printtty(colorize('> ', PROMPT_COLOR) +
           "; Completion is activated using the tab (if supported by the terminal)")

    for i in files:
        load_relation(i)

    readline.set_completer(completer.complete)

    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('set editing-mode emacs')
    readline.set_completer_delims(" ")

    while True:
        try:

            line = input(colorize('> ' if TTY else '', PROMPT_COLOR))
            if isinstance(line, str) and len(line) > 0:
                exec_line(line)
        except KeyboardInterrupt:
            if TTY:
                print ('^C\n')
                continue
            else:
                break
        except EOFError:
            printtty()
            sys.exit(0)
Ejemplo n.º 21
0
	def __init__(self):
		self.modules = None
		self.currentmodule = None
		self.db = db_handler.DBHandler()
		self.commands = [("search", "Search for malwares according to a filter,\n\t\t\te.g 'search cpp worm'."),
						 ("list all", "Lists all available modules"),
						 ("use", "Selects a malware by ID"),
						 ("info", "Retreives information about malware"),
						 ("get", "Downloads selected malware"),
						 ("report-mal", "Report a malware you found"),
						 ("update-db", "Updates the databse"),
						 ("help", "Displays this help..."),
						 ("exit", "Exits...")]

		self.commandsWithoutDescription = {'search': '', 'list all': '', 'use': '', 'info': '',
										   'get': '', 'report-mal': '', 'update-db': '', 'help': '', 'exit': ''}

		self.searchmeth = [("arch", "which architecture etc; x86, x64, arm7 so on..."),
						   ("plat",
							"platform: win32, win64, mac, android so on..."),
						   ("lang", "c, cpp, vbs, bin so on..."),
						   ("vip", "1 or 0")]

		self.modules = self.GetPayloads()
		completer = globals.Completer(self.commandsWithoutDescription)

		readline.parse_and_bind("tab: complete")
		readline.set_completer(completer.complete)
Ejemplo n.º 22
0
    def FastLogin(self):
        data = map(str, DBQuery().AuthIP())
        ip_user = [v.replace('\t', ' ') for v in data]
        
        # raw_input tab 
        def complete(text, state):
            for i in ip_user:
                if i.startswith(text):
                    if not state:
                        return i
                    else:
                        state -= 1
        readline.parse_and_bind("tab: complete")
        readline.set_completer(complete)

        while True:
            ip_user = raw_input('Please input ip and user > ').strip().split()
            if 'q' in ip_user:
                self.Main()
            elif len(ip_user) == 2:
                remote_ip, remote_user = ip_user[0], ip_user[1]
                self.Connection(remote_ip, remote_user)
                break
            else: 
                continue
Ejemplo n.º 23
0
def shell(vars, message="Entering Interactive Python Interpreter",
            prompt="(py)pylans:>", exit_msg="Returning to pylans cli"):
    '''
        Start an interactive (i)python interpreter on the commandline.
        This blocks, so don't call from twisted, but in a thread or from Cmd is fine.
        
        :param vars: variables to make available to interpreter
        :type vars: dict
    '''
    try:
        import IPython
        version = IPython.__version__

        if version.startswith('0.10'):
            return _10shell(vars, message, prompt, exit_msg)
            
        elif version.startswith('0.11') or \
             version.startswith('0.12'):
             return _12shell(vars, message, prompt, exit_msg)

        else:
            raise ImportError('unknown IPython version: {0}'.format(version))

    except (ImportError, AttributeError):
        logger.error('could not find a compatible version of IPython', exc_info=True)
        ## this doesn't quite work right, in that it doesn't go to the right env
        ## so we just fail.
        import code
        import rlcompleter
        import readline
        readline.parse_and_bind("tab: complete")
        # calling this with globals ensures we can see the environment
        print message
        shell = code.InteractiveConsole(vars)
        return shell.interact
Ejemplo n.º 24
0
    def handle(self, options, global_options, *args):
        namespace = self.make_shell_env(global_options)
        try:
            import readline
        except ImportError:
            print "Module readline not available."
        else:
            import rlcompleter
            readline.parse_and_bind("tab: complete")
        
#        if options.ipython:
#            try:
#                import IPython
#            except ImportError:
#                pass
#            else:
#                sh = IPython.Shell.IPShellEmbed(banner=self.banner)
#                sh(global_ns={}, local_ns=namespace)
#                return
        from code import interact, InteractiveConsole
        Interpreter = MyInteractive(namespace)
        if args:
            def call():
                execfile(args[0], namespace)
        else:
            call = None
        Interpreter.interact(self.banner, call=call)
Ejemplo n.º 25
0
def drop_to_shell(local):
    import rlcompleter
    import readline
    import code

    readline.parse_and_bind("tab: complete")
    code.interact(local=local)
Ejemplo n.º 26
0
 def completer(self,func):
     def keys():
         keys = [i for i in func()]
         return keys        
     readline.set_completer(SimpleCompleter(keys()).complete)
     readline.set_completer_delims('')
     readline.parse_and_bind('tab: complete')
Ejemplo n.º 27
0
Archivo: __init__.py Proyecto: gera/spg
def get_input_with_readline(filename):
	"""
	sets up readline support for entering sitenames, completed from the
	existing list and accepts a line of input.
	"""
	if not os.path.exists(filename):
		file(filename, "w").close()

	all_lines = map(lambda x: x.strip(), file(filename).readlines())

	def  completer(text, state):
		"""
		custom readline completer
		"""
		candidates = filter(lambda x: x.startswith(text), all_lines)
		if state <= len(candidates):
			return candidates[state-1]
		else:
			return None

	try:
		import readline
		readline.set_completer(completer)
		readline.read_history_file(filename)
		readline.parse_and_bind('tab: complete')
		if hasattr(readline, 'readline'):
			print "sitename: ",
			readline._issued = True
			return readline.readline(history=all_lines, histfile=None)
		else:
			return raw_input("sitename: ")
	except:
		# no readline?
		return raw_input("sitename: ")
Ejemplo n.º 28
0
def interpreter(lang=None):
    """
    zhpy interpreter

Accept args:
    lang:
        interpreter language
    """
    try:
        import readline
        import rlcompleter
        readline.parse_and_bind("tab: complete")
    except ImportError:
        pass

    con = ZhPyConsole()
    if lang == 'tw':
        banner = '周蟒 %s 於 %s 基於 Python %s'%(version, sys.platform,
                                                  sys.version.split()[0])
        if sys.platform == 'win32':
            banner = unicode(banner, 'utf-8').encode(sys.stdout.encoding)
    elif lang == 'cn':
        banner = '周蟒 %s 于 %s 基于 Python %s'%(version, sys.platform,
                                                  sys.version.split()[0])
        if sys.platform == 'win32':
            banner = unicode(banner, 'utf-8').encode(sys.stdout.encoding)
    else:
        banner = 'zhpy %s in %s on top of Python %s'%(version, sys.platform,
                                                  sys.version.split()[0])
    annotator()
    # able to import modules in current directory
    sys.path.insert(0, '')
    con.interact(banner)
Ejemplo n.º 29
0
    def plain(self):
        """Plain Python shell."""
        from nikola import Nikola
        try:
            import conf
            SITE = Nikola(**conf.__dict__)
            SITE.scan_posts()
            gl = {'conf': conf, 'SITE': SITE, 'Nikola': Nikola}
        except ImportError:
            LOGGER.error("No configuration found, cannot run the console.")
        else:
            import code
            try:
                import readline
            except ImportError:
                pass
            else:
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(gl).complete)
                readline.parse_and_bind("tab:complete")

            pythonrc = os.environ.get("PYTHONSTARTUP")
            if pythonrc and os.path.isfile(pythonrc):
                try:
                    execfile(pythonrc)  # NOQA
                except NameError:
                    pass

            code.interact(local=gl, banner=self.header.format('Python'))
Ejemplo n.º 30
0
def main():
    global __prompt
    global __time_to_go

    print("JSON configuration utility version (1.0.0)")
    handle_arguments()

    readline.set_completer_delims("\t\n")
    readline.parse_and_bind("tab: complete")
    readline.set_completer(auto_complete)

    command = ""
    while True:
        try:
            user_input = input(__prompt + " ").strip()
        except KeyboardInterrupt:
            print()
            if __time_to_go:
                exit_command()
            else:
                __time_to_go = True
                print("Press ^C again to close. Running another command resets this.")
                continue

        if not user_input:
            continue

        run_command(user_input)
        __time_to_go = False
Ejemplo n.º 31
0
def setup_readline():
    """Initialize the readline module."""
    # Edited to work with pyenv
    histpath = os.path.join(os.path.expanduser("~"), ".pyenv", "versions",
                            sys.version.split(' ')[0], "share")

    if sys.version[0] == '2':
        histfile = os.path.join(histpath, "py2hist")
    else:
        histfile = os.path.join(histpath, "py3hist")
    if not os.path.exists(histpath):
        os.mkdir(histpath)
    atexit.register(readline.write_history_file, histfile)
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass
    # Complete with the tab key. M-tab completes on local file names.
    readline.parse_and_bind("tab: complete")
    # readline indentation keybinding
    # Control-j: indent 4 spaces
    # Control-u: unindent 4 spaces
    # First, create some dummy shortcuts:
    # Add four spaces:
    readline.parse_and_bind(r'"\M-j": "    "')
    # Delete four characters (behind point):
    readline.parse_and_bind(r'"\M-h": delete-char')
    readline.parse_and_bind(r'"\M-k": "\M-h\M-h\M-h\M-h"')
    # Move point forward four characters:
    readline.parse_and_bind(r'"\M-e": "\C-f\C-f\C-f\C-f"')
    # Move point backward four characters:
    readline.parse_and_bind(r'"\M-g": "\C-b\C-b\C-b\C-b"')
    # Second, define another set-mark shortcut, since it only seems to
    # work when bound to a letter key.
    readline.parse_and_bind(r'"\M-\C-j": set-mark')
    # C-j macro: set mark, go to the beginning of the line, add four
    # spaces, exchange point and mark, and then move forward four
    # characters to the same point in the text where you were before,
    # regardless of the new indentation.
    readline.parse_and_bind(r'"\C-j": "\M-\C-j\C-a\M-j\C-x\C-x\M-e"')
    # C-u macro: Move back four characters, set mark, move to the
    # beginning of the line, move forward four characters, delete four
    # characters, then exchange mark and point. This would be shorter
    # readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-e\M-k\C-x\C-x"')
    readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-k\C-x\C-x"')
    # load readline history
    readline.set_pre_input_hook(rl_autoindent)
    readline.set_completion_display_matches_hook(comp_disp_matches)
Ejemplo n.º 32
0
   def run(self):
      try:
	def_manual = raw_input("¿Cargar configuración por defecto?\n(s/n)>")
      except EOFError: #EOF
	self.stop = False
	self.q_stop.put("STOP")
	sys.exit(1)  
      if def_manual == "s":
	print "Cargando configuración inicial por defecto."
	for key, value in self.dic_com_default.iteritems():
	  if value != "":
	    time.sleep(4)
	    s = self.nombreModulo
	    s += ":"
	    s += value
	    print "Comando enviado: {}".format(s)
	    self.q.put(s)
    
      readline.parse_and_bind('set editing-mode vi')
      
      self.q_stop.queue.clear()
      for k, v in self.dicpines_str.iteritems():
	if v == "Pulsador":
	  hilo_boton = T_pulsador(self.q, self.q_T_Boton, self.q_stop, k)
	  
	  hilo_boton.start()
      
      print "Introduzca -comando- para invocar un comando directamente\n"

      while True:
	
	time.sleep(1)
	
	self.pasa = 0
	#---#
	try:
	  interactuado = raw_input("Nombre del dispositivo con el que interactuar>")
	except EOFError:
	  self.stop = False
	  self.q_stop.put("STOP")
	  print "--Saliendo del programa--"
	  break
	if len(interactuado) == 0:
	  continue
	
	if interactuado == "comando":
	  try:
	    s = raw_input("Esperando comandos> ")
	  except EOFError: #EOF
	    self.stop = False
	    self.q_stop.put("STOP")
	    print "--Saliendo del programa--"
	    break
	  if len(s) == 0:
	    continue
	  self.q.put(s)
	  continue
	  
	if self.dicdispositivos.has_key(interactuado):
	  print "El dispositivo '{}' es un {}.\n".format(interactuado, self.dicdispositivos[interactuado])
	else:
	  print "El nombre de dispositivo indicado no existe, pruebe otra vez\n"
	  continue
	print "Para el dispositivo '{}' existen las siguientes acciones:".format(interactuado)
	tipo_actual = self.dicdispositivos[interactuado]
	self.dic_options[tipo_actual](self, interactuado)
	
	#---#
	if self.pasa == 0:
	  try:
	    c_manual = raw_input("¿Introducir el comando indicado?\n(s/n)>")
	  except EOFError: #EOF
	    self.stop = False
	    self.q_stop.put("STOP")
	    break    
	  if c_manual == "s":
	    s = self.com_M
	  else:
	    try:
	      s = raw_input("Esperando comandos> ")
	    except EOFError: #EOF
	      self.stop = False
	      self.q_stop.put("STOP")
	      break
	  if len(s) == 0:
	    continue
	  
	  self.q.put(s)
def run_interactive(group_name):
    c = MoveGroupCommandInterpreter()
    if len(group_name) > 0:
        c.execute("use " + group_name)
        print("Group Name Set")
    completer = SimpleCompleter(get_context_keywords(c))
    readline.set_completer(completer.complete)

    print()
    print(
        bcolors.HEADER +
        "Waiting for commands. Type 'help' to get a list of known commands." +
        bcolors.ENDC)
    print()
    readline.parse_and_bind('tab: complete')

    while not rospy.is_shutdown():
        cmd = ""
        try:
            name = ""
            ag = c.get_active_group()
            if ag != None:
                name = ag.get_name()
            cmd = input(bcolors.OKBLUE + name + '> ' + bcolors.ENDC)
        except:
            break
        cmdorig = cmd.strip()
        if cmdorig == "":
            continue
        cmd = cmdorig.lower()

        if cmd == "q" or cmd == "quit" or cmd == "exit":
            break
        if cmd == "host":
            print_message(MoveGroupInfoLevel.INFO,
                          "Master is '" + os.environ['ROS_MASTER_URI'] + "'")
            continue
        print("Recieved Command", cmdorig)
        if (cmdorig == "ik"):
            print("Give the x y z inputs")
            x, y, z = raw_input().split(' ')
            ''' call inverse kinematics and get current state'''
            cmdorig = "current"
            (level, msg) = c.execute(cmdorig)
            completer.set_options(get_context_keywords(c))
            joints = inverse_kinematics(x, y, z, msg)

            ## rec c
            cmdorig = "rec c"
            (level, msg) = c.execute(cmdorig)
            print_message(level, msg)
            completer.set_options(get_context_keywords(c))

            ## goal = c
            cmdorig = "goal = c"
            (level, msg) = c.execute(cmdorig)
            print_message(level, msg)
            completer.set_options(get_context_keywords(c))

            ## setting joints
            for i in range(0, len(joints)):
                print("goal", i)
                cmdorig = "goal[" + str(i) + "]" + "=" + str(joints[i])
                (level, msg) = c.execute(cmdorig)
                print_message(level, msg)
                completer.set_options(get_context_keywords(c))

            ## finally execute
            cmdorig = "go goal"
            (level, msg) = c.execute(cmdorig)
            print_message(level, msg)
            completer.set_options(get_context_keywords(c))
        else:
            (level, msg) = c.execute(cmdorig)
            print_message(level, msg)
            # update the set of keywords
            completer.set_options(get_context_keywords(c))
Ejemplo n.º 34
0
# -*- coding:utf-8 -*-

# Author:Chuixin Zeng

import sys
import readline
import rlcompleter

if sys.platform == 'darwin' and sys.version_info[0] == 2:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")  # linux and python3 on mac
    '''
     用法

     localhost:~ jieli$ python
     Python 2.7.10 (default, Oct 23 2015, 18:05:06)
     [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
     Type "help", "copyright", "credits" or "license" for more information.
     >>> import tab

     '''
def interact(mydict=None, argv=None, mybanner=None, loglevel=20):
    global session
    import code, sys, cPickle, os, getopt, re
    from config import conf
    conf.interactive = True
    if loglevel is not None:
        conf.logLevel = loglevel

    the_banner = "Welcome to Scapy (%s)"
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    if argv is None:
        argv = sys.argv

    import atexit
    try:
        import rlcompleter, readline
    except ImportError:
        log_loading.info("Can't load Python libreadline or completer")
        READLINE = 0
    else:
        READLINE = 1

        class ScapyCompleter(rlcompleter.Completer):
            def global_matches(self, text):
                matches = []
                n = len(text)
                for lst in [dir(__builtin__), session.keys()]:
                    for word in lst:
                        if word[:n] == text and word != "__builtins__":
                            matches.append(word)
                return matches

            def attr_matches(self, text):
                m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
                if not m:
                    return
                expr, attr = m.group(1, 3)
                try:
                    object = eval(expr)
                except:
                    object = eval(expr, session)
                if isinstance(object, Packet) or isinstance(
                        object, Packet_metaclass):
                    words = filter(lambda x: x[0] != "_", dir(object))
                    words += [x.name for x in object.fields_desc]
                else:
                    words = dir(object)
                    if hasattr(object, "__class__"):
                        words = words + rlcompleter.get_class_members(
                            object.__class__)
                matches = []
                n = len(attr)
                for word in words:
                    if word[:n] == attr and word != "__builtins__":
                        matches.append("%s.%s" % (expr, word))
                return matches

        readline.set_completer(ScapyCompleter().complete)
        readline.parse_and_bind("C-o: operate-and-get-next")
        readline.parse_and_bind("tab: complete")

    session = None
    session_name = ""
    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    iface = None
    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" %
                                     " ".join(opts[1]))

    except getopt.GetoptError, msg:
        log_loading.error(msg)
        sys.exit(1)
# tab completion
def complete(text, state):
    a = (glob.glob(text + '*') + [None])[state].replace(
        "__init__.py", "").replace(".py", "").replace("LICENSE", "").replace(
            "README.md", "").replace("config", "").replace("ptf", "").replace(
                "readme", "").replace("src", "").replace("         ", "") + "/"
    a = a.replace("//", "/")
    if os.path.isfile(a[:-1] + ".py"):
        return a[:-1]
    else:
        return a


readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
# end tab completion

# color scheme for core


class bcolors:
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    DARKCYAN = '\033[36m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    BOLD = '\033[1m'
Ejemplo n.º 37
0
if extra:
    lines = extra
else:
    try:
        import readline
    except ImportError:
        log('* readline module not available: line editing disabled.\n')
        readline = None

    if readline:
        readline.set_completer_delims(' \t\n\r/')
        readline.set_completer(completer)
        if sys.platform.startswith('darwin'):
            # MacOS uses a slightly incompatible clone of libreadline
            readline.parse_and_bind('bind ^I rl_complete')
        readline.parse_and_bind('tab: complete')
    lines = inputiter()

for line in lines:
    if not line.strip():
        continue
    words = [word for (wordstart, word) in shquote.quotesplit(line)]
    cmd = words[0].lower()
    #log('execute: %r %r\n' % (cmd, parm))
    try:
        if cmd == 'ls':
            # FIXME: respect pwd (perhaps via ls accepting resolve path/parent)
            do_ls(repo, words[1:])
        elif cmd == 'cd':
            np = pwd
Ejemplo n.º 38
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('module', nargs='?', help='Module')
    parser.add_argument('--noprelude',
                        action='store_true',
                        help='Include prelude')
    args = parser.parse_args()

    # State
    mod = {}
    last = None
    bindings = {}

    if args.module:
        with open(args.module) as fd:
            mod = module(fd.read())

    if not args.noprelude:
        mod.update(prelude)

    print banner
    readline.parse_and_bind("tab: complete")
    readline.set_completer(partial(completer, mod))

    while True:
        try:
            line = raw_input('>> ').strip()
        except EOFError:
            break

        #-----------------------------------------------
        if line.startswith('?'):
            at = aparse(line[1:])
            matcher = partial(match, freev(at))
            matched, localbind = matcher(last)

            # TODO: Use dict
            #bindings.update(localbind)

            #if matched:
            #    print bindings
            #else:
            #    print 'failed'

        #-----------------------------------------------
        elif line.startswith('!'):
            try:
                rr = mod[line[1:].strip()]
                last = rr.rewrite(last)
                print last
            except KeyError:
                print "No such rule or strategy '%s'" % line[1:]
            except NoMatch:
                print 'failed'

        #-----------------------------------------------
        elif line.startswith(':show') or line.startswith(':s'):
            try:
                rr = mod[line[1:].strip()]
                print rr
            except KeyError:
                print "No such rule or strategy '%s'" % line[1:]

        #-----------------------------------------------
        elif line.startswith(':type') or line.startswith(':t'):
            try:
                at = aparse(line[2:])
                print type(at).__name__
            except Exception as e:
                print e

        #-----------------------------------------------
        elif line.startswith(':bindings'):
            if bindings:
                pprint.pprint(bindings)
            continue

        #-----------------------------------------------
        elif line.startswith(':let'):
            env = module(line[4:], _env=mod)
            mod.update(env)

        #-----------------------------------------------
        elif line.startswith(':load'):
            fname = line[5:].strip()
            try:
                contents = open(fname).read()
                mod.update(module(contents))
            except IOError:
                print "No such module", fname

        #-----------------------------------------------
        elif line.startswith(':browse'):
            pprint.pprint(mod)

        #-----------------------------------------------
        elif line.startswith(':help'):
            print help
            pass

        #-----------------------------------------------
        else:
            bindings = {}
            try:
                last = aparse(line)
                print last
            except EOFError:
                pass
            except Exception as e:
                print traceback.format_exc()
Ejemplo n.º 39
0
def main():
    import ipy_profile_sh

    o = ip.options

    o.autocall = 1
    o.system_verbose = 0

    import os
    from datetime import date

    # this is not elegant at all
    GIT_BRACKET_OPEN = \
"""
os.popen(" \
    git branch >/dev/null 2>/dev/null && echo '('; \
    ").read().rstrip()
"""

    GIT_BRACKET_CLOSE = \
"""
os.popen(" \
    git branch >/dev/null 2>/dev/null && echo ')'; \
    ").read().rstrip()
"""

    # FIXME: git-branch's output should not be used in scripts
    # FIXME: parse "git symbolic-ref HEAD 2>/dev/null" instead
    GIT_BRANCH = \
"""
os.popen(" \
    git branch 2>/dev/null | sed -e '/^\s/d' -e 's/^\*\s//'; \
    ").read().rstrip()
"""

    GIT_COLON = \
"""
os.popen(" \
    git branch >/dev/null 2>/dev/null && echo ':'; \
    ").read().rstrip()
"""

    GIT_MODIFIED = \
"""
os.popen(' \
    diff=`git diff 2>/dev/null`; \
    test -n "$diff" && echo "!"; \
    ').read().rstrip()
"""

    GIT_ON = \
"""
os.popen(" \
    git branch >/dev/null 2>/dev/null && echo 'on'; \
    ").read().rstrip()
"""

    GIT_REVSTRING = \
"""
os.popen(" \
    git describe --tags --always 2>/dev/null; \
    ").read().rstrip()
"""

    GIT_STAGED = \
"""
os.popen(' \
    diff=`git diff --cached 2>/dev/null`; \
    test -n "$diff" && echo "+"; \
    ').read().rstrip()
"""

    GIT_UNTRACKED = \
"""
os.popen(' \
    filelist=`git ls-files --others --exclude-standard 2>/dev/null`; \
    test -n "$filelist" && echo "?"; \
    ').read().rstrip()
"""

    o.prompt_in1 = r"\C_Green\h \C_Cyan\Y5\C_Normal ${%s} \C_Cyan${%s}\C_Brown${%s}${%s}${%s}\n\C_Green\N \C_Normal\Y1\C_Normal${%s}\C_Cyan${%s}\C_LightGreen${%s}\C_LightRed${%s}${%s} \C_Brown★ " % \
(
        GIT_ON,
        GIT_BRANCH,
        GIT_BRACKET_OPEN,
        GIT_REVSTRING,
        GIT_BRACKET_CLOSE,
        GIT_COLON,
        GIT_BRANCH,
        GIT_STAGED,
        GIT_MODIFIED,
        GIT_UNTRACKED
    )
    o.prompt_in2 = r'\C_Brown⋮ '
    o.prompt_out = r'\# ➜ '

    o.confirm_exit = 0
    o.banner = 0

    # for sane integer division that converts to float (1/2 == 0.5)
    o.autoexec.append('from __future__ import division')

    # get return values of commands
    STATUS_FUNCTION = \
"""
def system_return_code(cmd):
    status = os.system(cmd) >> 8  # high-order byte is the exit status
    if (status != 0):
        return status

def magic_cd_fallback_system(cmd):
    path = os.path.expanduser(cmd)

    if os.path.isdir(path):
        _ip.magic('%cd ' + cmd)
        set_term_title(os.path.basename(path))
        return

    return system_return_code(cmd)

_ip.system=magic_cd_fallback_system
"""

    o.autoexec.append(STATUS_FUNCTION)

    o.autoexec.append('from IPython.platutils_posix import set_term_title')
    o.autoexec.append("set_term_title('~')")

    # Crtl + L clears the screen
    import readline
    readline.parse_and_bind('"\C-l":clear-screen')

    # For %tasks and %kill
    import jobctrl

    # Tab completer that is not quite so picky (i.e.
    # "foo".<TAB> and str(2).<TAB> will work). Complete
    # at your own risk!
    import ipy_greedycompleter
Ejemplo n.º 40
0
 def set_ctrl_completer():
     completer = auto_complete(self.target_comands)
     readline.set_completer(completer.complete)
     readline.parse_and_bind('tab: complete')
Ejemplo n.º 41
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.
        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                readline.read_history_file(self.conf['history_file'])
                readline.set_history_length(self.conf['history_size'])
            except IOError:
                # if history file does not exist
                try:
                    open(self.conf['history_file'], 'w').close()
                    readline.read_history_file(self.conf['history_file'])
                except IOError:
                    pass
            readline.set_completer_delims(
                readline.get_completer_delims().replace('-', ''))
            self.old_completer = readline.get_completer()
            readline.set_completer(self.complete)
            readline.parse_and_bind(self.completekey + ": complete")
        try:
            if self.intro and isinstance(self.intro, str):
                self.stdout.write("%s\n" % self.intro)
            if self.conf['login_script']:
                utils.exec_cmd(self.conf['login_script'])
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            # raw_input renamed as input in py3
                            try:
                                line = raw_input(self.conf['promptprint'])
                            except NameError:
                                line = input(self.conf['promptprint'])
                        except EOFError:
                            line = 'EOF'
                        except KeyboardInterrupt:
                            self.stdout.write('\n')
                            line = ''
                    else:
                        self.stdout.write(self.conf['promptprint'])
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            # chop \n
                            line = line[:-1]
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    readline.set_completer_delims(
                        readline.get_completer_delims().replace('-', ''))
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
            try:
                readline.write_history_file(self.conf['history_file'])
            except IOError:
                self.log.error('WARN: couldn\'t write history '
                               'to file %s\n' % self.conf['history_file'])
Ejemplo n.º 42
0
import time
from time import sleep
import base64
import sys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
import logging, optparse, os
from os import system, name
import readline
import threading
from threading import Thread, Lock

# set up readline
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')


# user info
userid = "ID4XXXXXX"
apikid = "KIDXXXXXX"

# prod url 
url = "wss://ws.oceanex.pro/ws/v1"

class OceanExWSListener(object):
    def __init__(self, endpoint, logger, userid=None, apikid=None):
        self.url = endpoint
        self.uid = userid
        self.kid = apikid
Ejemplo n.º 43
0
def cb_injection_handler(url, delay, filename, http_request_method):

    counter = 1
    vp_flag = True
    no_result = True
    is_encoded = False
    export_injection_info = False
    injection_type = "results-based command injection"
    technique = "classic injection technique"

    if not settings.LOAD_SESSION:
        info_msg = "Testing the " + technique + "... "
        sys.stdout.write(settings.print_info_msg(info_msg))
        sys.stdout.flush()
        if settings.VERBOSITY_LEVEL >= 1:
            print ""

    i = 0
    # Calculate all possible combinations
    total = len(settings.WHITESPACE) * len(settings.PREFIXES) * len(
        settings.SEPARATORS) * len(settings.SUFFIXES)
    for whitespace in settings.WHITESPACE:
        for prefix in settings.PREFIXES:
            for suffix in settings.SUFFIXES:
                for separator in settings.SEPARATORS:

                    # If a previous session is available.
                    if settings.LOAD_SESSION and session_handler.notification(
                            url, technique):
                        url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, delay, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(
                            url, http_request_method)
                        checks.check_for_stored_tamper(payload)

                    else:
                        i = i + 1
                        # Check for bad combination of prefix and separator
                        combination = prefix + separator
                        if combination in settings.JUNK_COMBINATION:
                            prefix = ""

                        # Change TAG on every request to prevent false-positive results.
                        TAG = ''.join(
                            random.choice(string.ascii_uppercase)
                            for i in range(6))

                        randv1 = random.randrange(100)
                        randv2 = random.randrange(100)
                        randvcalc = randv1 + randv2

                        # Define alter shell
                        alter_shell = menu.options.alter_shell

                        try:
                            if alter_shell:
                                # Classic -alter shell- decision payload (check if host is vulnerable).
                                payload = cb_payloads.decision_alter_shell(
                                    separator, TAG, randv1, randv2)
                            else:
                                # Classic decision payload (check if host is vulnerable).
                                payload = cb_payloads.decision(
                                    separator, TAG, randv1, randv2)

                            # Define prefixes & suffixes
                            payload = parameters.prefixes(payload, prefix)
                            payload = parameters.suffixes(payload, suffix)

                            # Whitespace fixation
                            payload = re.sub(" ", whitespace, payload)

                            # Check for base64 / hex encoding
                            payload = checks.perform_payload_encoding(payload)

                            # Check if defined "--verbose" option.
                            if settings.VERBOSITY_LEVEL == 1:
                                print settings.print_payload(payload)
                            elif settings.VERBOSITY_LEVEL > 1:
                                info_msg = "Generating a payload for injection..."
                                print settings.print_info_msg(info_msg)
                                print settings.print_payload(payload)

                            # Cookie Injection
                            if settings.COOKIE_INJECTION == True:
                                # Check if target host is vulnerable to cookie injection.
                                vuln_parameter = parameters.specify_cookie_parameter(
                                    menu.options.cookie)
                                response = cb_injector.cookie_injection_test(
                                    url, vuln_parameter, payload)

                            # User-Agent Injection
                            elif settings.USER_AGENT_INJECTION == True:
                                # Check if target host is vulnerable to user-agent injection.
                                vuln_parameter = parameters.specify_user_agent_parameter(
                                    menu.options.agent)
                                response = cb_injector.user_agent_injection_test(
                                    url, vuln_parameter, payload)

                            # Referer Injection
                            elif settings.REFERER_INJECTION == True:
                                # Check if target host is vulnerable to referer injection.
                                vuln_parameter = parameters.specify_referer_parameter(
                                    menu.options.referer)
                                response = cb_injector.referer_injection_test(
                                    url, vuln_parameter, payload)

                            # Custom HTTP header Injection
                            elif settings.CUSTOM_HEADER_INJECTION == True:
                                # Check if target host is vulnerable to custom http header injection.
                                vuln_parameter = parameters.specify_custom_header_parameter(
                                    settings.INJECT_TAG)
                                response = cb_injector.custom_header_injection_test(
                                    url, vuln_parameter, payload)

                            else:
                                # Check if target host is vulnerable.
                                response, vuln_parameter = cb_injector.injection_test(
                                    payload, http_request_method, url)

                            # Try target page reload (if it is required).
                            if settings.URL_RELOAD:
                                response = requests.url_reload(url, delay)
                            # Evaluate test results.
                            shell = cb_injector.injection_test_results(
                                response, TAG, randvcalc)

                            if not settings.VERBOSITY_LEVEL >= 1:
                                percent = ((i * 100) / total)
                                float_percent = "{0:.1f}".format(
                                    round(((i * 100) / (total * 1.0)), 2))

                                if shell == False:
                                    info_msg = "Testing the " + technique + "... " + "[ " + float_percent + "%" + " ]"
                                    sys.stdout.write(
                                        "\r" +
                                        settings.print_info_msg(info_msg))
                                    sys.stdout.flush()

                                if float(float_percent) >= 99.9:
                                    if no_result == True:
                                        percent = Fore.RED + "FAILED" + Style.RESET_ALL
                                    else:
                                        percent = str(float_percent) + "%"
                                elif len(shell) != 0:
                                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                                else:
                                    percent = str(float_percent) + "%"
                                info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]"
                                sys.stdout.write(
                                    "\r" + settings.print_info_msg(info_msg))
                                sys.stdout.flush()

                        except KeyboardInterrupt:
                            raise

                        except SystemExit:
                            raise

                        except:
                            continue

                    # Yaw, got shellz!
                    # Do some magic tricks!
                    if shell:
                        found = True
                        no_result = False

                        if settings.COOKIE_INJECTION == True:
                            header_name = " cookie"
                            found_vuln_parameter = vuln_parameter
                            the_type = " parameter"

                        elif settings.USER_AGENT_INJECTION == True:
                            header_name = " User-Agent"
                            found_vuln_parameter = ""
                            the_type = " HTTP header"

                        elif settings.REFERER_INJECTION == True:
                            header_name = " Referer"
                            found_vuln_parameter = ""
                            the_type = " HTTP header"

                        elif settings.CUSTOM_HEADER_INJECTION == True:
                            header_name = " " + settings.CUSTOM_HEADER_NAME
                            found_vuln_parameter = ""
                            the_type = " HTTP header"

                        else:
                            header_name = ""
                            the_type = " parameter"
                            if http_request_method == "GET":
                                found_vuln_parameter = parameters.vuln_GET_param(
                                    url)
                            else:
                                found_vuln_parameter = vuln_parameter

                        if len(found_vuln_parameter) != 0:
                            found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'"

                        # Print the findings to log file.
                        if export_injection_info == False:
                            export_injection_info = logs.add_type_and_technique(
                                export_injection_info, filename,
                                injection_type, technique)
                        if vp_flag == True:
                            vp_flag = logs.add_parameter(
                                vp_flag, filename, the_type, header_name,
                                http_request_method, vuln_parameter, payload)
                        logs.update_payload(filename, counter, payload)
                        counter = counter + 1

                        if not settings.VERBOSITY_LEVEL >= 1 and not settings.LOAD_SESSION:
                            print ""

                        # Print the findings to terminal.
                        success_msg = "The"
                        if found_vuln_parameter == " ":
                            success_msg += http_request_method + ""
                        success_msg += the_type + header_name
                        success_msg += found_vuln_parameter + " seems injectable via "
                        success_msg += "(" + injection_type.split(
                            " ")[0] + ") " + technique + "."
                        print settings.print_success_msg(success_msg)
                        print settings.SUB_CONTENT_SIGN + "Payload: " + re.sub(
                            "%20", " ", re.sub("%2B", "+",
                                               payload)) + Style.RESET_ALL
                        # Export session
                        if not settings.LOAD_SESSION:
                            session_handler.injection_point_importation(
                                url,
                                technique,
                                injection_type,
                                separator,
                                shell[0],
                                vuln_parameter,
                                prefix,
                                suffix,
                                TAG,
                                alter_shell,
                                payload,
                                http_request_method,
                                url_time_response=0,
                                delay=0,
                                how_long=0,
                                output_length=0,
                                is_vulnerable=menu.options.level)
                        else:
                            whitespace = settings.WHITESPACE[0]
                            settings.LOAD_SESSION = False

                        # Check for any enumeration options.
                        new_line = True
                        if settings.ENUMERATION_DONE == True:
                            while True:
                                if not menu.options.batch:
                                    question_msg = "Do you want to enumerate again? [Y/n] > "
                                    enumerate_again = raw_input(
                                        "\n" + settings.print_question_msg(
                                            question_msg)).lower()
                                else:
                                    enumerate_again = ""
                                if len(enumerate_again) == 0:
                                    enumerate_again = "y"
                                if enumerate_again in settings.CHOICE_YES:
                                    cb_enumeration.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename,
                                        delay)
                                    #print ""
                                    break
                                elif enumerate_again in settings.CHOICE_NO:
                                    new_line = False
                                    break
                                elif enumerate_again in settings.CHOICE_QUIT:
                                    sys.exit(0)
                                else:
                                    err_msg = "'" + enumerate_again + "' is not a valid answer."
                                    print settings.print_error_msg(err_msg)
                                    pass
                        else:
                            if menu.enumeration_options():
                                cb_enumeration.do_check(
                                    separator, TAG, prefix, suffix, whitespace,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, delay)

                        if not menu.file_access_options(
                        ) and not menu.options.os_cmd and new_line:
                            print ""

                        # Check for any system file access options.
                        if settings.FILE_ACCESS_DONE == True:
                            if settings.ENUMERATION_DONE != True:
                                print ""
                            while True:
                                if not menu.options.batch:
                                    question_msg = "Do you want to access files again? [Y/n] > "
                                    sys.stdout.write(
                                        settings.print_question_msg(
                                            question_msg))
                                    file_access_again = sys.stdin.readline(
                                    ).replace("\n", "").lower()
                                else:
                                    file_access_again = ""
                                if len(file_access_again) == 0:
                                    file_access_again = "y"
                                if file_access_again in settings.CHOICE_YES:
                                    cb_file_access.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename,
                                        delay)
                                    print ""
                                    break
                                elif file_access_again in settings.CHOICE_NO:
                                    break
                                elif file_access_again in settings.CHOICE_QUIT:
                                    sys.exit(0)
                                else:
                                    err_msg = "'" + file_access_again + "' is not a valid answer."
                                    print settings.print_error_msg(err_msg)
                                    pass
                        else:
                            if menu.file_access_options():
                                if not menu.enumeration_options():
                                    print ""
                                cb_file_access.do_check(
                                    separator, TAG, prefix, suffix, whitespace,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, delay)
                                print ""

                        # Check if defined single cmd.
                        if menu.options.os_cmd:
                            if not menu.file_access_options():
                                print ""
                            cb_enumeration.single_os_cmd_exec(
                                separator, TAG, prefix, suffix, whitespace,
                                http_request_method, url, vuln_parameter,
                                alter_shell, filename, delay)

                        # Pseudo-Terminal shell
                        go_back = False
                        go_back_again = False
                        while True:
                            if go_back == True:
                                break
                            # if settings.ENUMERATION_DONE == False and settings.FILE_ACCESS_DONE == False:
                            #   if settings.VERBOSITY_LEVEL >= 1:
                            #     print ""
                            if not menu.options.batch:
                                question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > "
                                sys.stdout.write(
                                    settings.print_question_msg(question_msg))
                                gotshell = sys.stdin.readline().replace(
                                    "\n", "").lower()
                            else:
                                gotshell = ""
                            if len(gotshell) == 0:
                                gotshell = "y"
                            if gotshell in settings.CHOICE_YES:
                                if not menu.options.batch:
                                    print ""
                                print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)"
                                if readline_error:
                                    checks.no_readline_module()
                                while True:
                                    try:
                                        if not readline_error:
                                            # Tab compliter
                                            readline.set_completer(
                                                menu.tab_completer)
                                            # MacOSX tab compliter
                                            if getattr(
                                                    readline, '__doc__', ''
                                            ) is not None and 'libedit' in getattr(
                                                    readline, '__doc__', ''):
                                                readline.parse_and_bind(
                                                    "bind ^I rl_complete")
                                            # Unix tab compliter
                                            else:
                                                readline.parse_and_bind(
                                                    "tab: complete")
                                        cmd = raw_input("""commix(""" +
                                                        Style.BRIGHT +
                                                        Fore.RED +
                                                        """os_shell""" +
                                                        Style.RESET_ALL +
                                                        """) > """)
                                        cmd = checks.escaped_cmd(cmd)
                                        if cmd.lower(
                                        ) in settings.SHELL_OPTIONS:
                                            go_back, go_back_again = shell_options.check_option(
                                                separator, TAG, cmd, prefix,
                                                suffix, whitespace,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell,
                                                filename, technique, go_back,
                                                no_result, delay,
                                                go_back_again)
                                            if go_back and go_back_again == False:
                                                break
                                            if go_back and go_back_again:
                                                return True
                                        else:
                                            # Command execution results.
                                            response = cb_injector.injection(
                                                separator, TAG, cmd, prefix,
                                                suffix, whitespace,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell,
                                                filename)
                                            # Try target page reload (if it is required).
                                            if settings.URL_RELOAD:
                                                response = requests.url_reload(
                                                    url, delay)
                                            if menu.options.ignore_session or \
                                               session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None:
                                                # Evaluate injection results.
                                                try:
                                                    shell = cb_injector.injection_results(
                                                        response, TAG, cmd)
                                                    shell = "".join(
                                                        str(p) for p in shell)
                                                except:
                                                    print ""
                                                    continue
                                                if not menu.options.ignore_session:
                                                    session_handler.store_cmd(
                                                        url, cmd, shell,
                                                        vuln_parameter)
                                            else:
                                                shell = session_handler.export_stored_cmd(
                                                    url, cmd, vuln_parameter)
                                            if shell:
                                                html_parser = HTMLParser.HTMLParser(
                                                )
                                                shell = html_parser.unescape(
                                                    shell)
                                                # Update logs with executed cmds and execution results.
                                                logs.executed_command(
                                                    filename, cmd, shell)
                                            if shell != "":
                                                if settings.VERBOSITY_LEVEL == 1:
                                                    print ""
                                                print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                                            else:
                                                if settings.VERBOSITY_LEVEL >= 1:
                                                    print ""
                                                err_msg = "The '" + cmd + "' command, does not return any output."
                                                print settings.print_critical_msg(
                                                    err_msg) + "\n"

                                    except KeyboardInterrupt:
                                        raise

                                    except SystemExit:
                                        raise

                            elif gotshell in settings.CHOICE_NO:
                                if checks.next_attack_vector(
                                        technique, go_back) == True:
                                    break
                                else:
                                    if no_result == True:
                                        return False
                                    else:
                                        return True

                            elif gotshell in settings.CHOICE_QUIT:
                                sys.exit(0)

                            else:
                                err_msg = "'" + gotshell + "' is not a valid answer."
                                print settings.print_error_msg(err_msg)
                                pass

    if no_result == True:
        print ""
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Ejemplo n.º 44
0
class sack(object):
    def __init__(self):
        self.point = "."
        self.suffix = "py"
        self.modules = []
        self.define = "modules"
        self.path = self.point + "/" + self.define
        self.listing = self.modules

    # Important: in the process of use is possible that will ask for the root
    def rootConnection(self): 
        if os.getuid() != 0:
            generals.Go("\t" + "-------------------")
            generals.Go("\t" + "> Welcome to " + config.nameFramework + " <")
            generals.Go("\t" + "-------------------")
            generals.Go(generals.Color["blueBold"] + "[*] " + generals.Color["white"] + "Hello " + generals.Color["greenBold"] + os.uname()[1] + "," + generals.Color["white"] + " I hope you enjoy my role")
            generals.Go(generals.Color["redBold"] + "[x] " + generals.Color["white"] + "You must run in mode " + generals.Color["whiteBold"] + "root" + generals.Color["white"] + " to be able to operate.")
            exit(0)

    # Design principal of the header of sack
    def header(self, totalModules):
        generals.Go("\033[H\033[J")
        generals.Go("\t\t" + generals.Color["green"] + "███████╗ █████╗  ██████╗██╗  ██╗")
        generals.Go("\t\t" + generals.Color["green"] + "██╔════╝██╔══██╗██╔════╝██║ ██╔╝")
        generals.Go("\t\t" + generals.Color["green"] + "███████╗███████║██║     █████╔╝ ")
        generals.Go("\t\t" + generals.Color["green"] + "╚════██║██╔══██║██║     ██╔═██╗ ")
        generals.Go("\t\t" + generals.Color["green"] + "███████║██║  ██║╚██████╗██║  ██╗")
        generals.Go("\t\t" + generals.Color["green"] + "╚══════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝")
        generals.Go("")
        generals.Go("\t" + generals.Color["yellowBold"] + "      .:::" + generals.Color["redBold"] + "> " + generals.Color["whiteBold"] + "Footprint track-sessions" + " " + generals.Color["redBold"] + "<"  + generals.Color["yellowBold"] + ":::.  " + generals.Color["white"]) 
        generals.Go("\t" + generals.Color["blueBold"]   + "     --------------------------------------" +  generals.Color["white"])
        generals.Go("\t" + generals.Color["whiteBold"]  + "     x    " + generals.Color["blueBold"] + "🌎   " + generals.Color["redBold"] + "Hack the world happy" +  generals.Color["blueBold"] + "  🌍" + "     " + generals.Color["whiteBold"] + "x")
        generals.Go("\t" + generals.Color["blueBold"]   + "     --------------------------------------" + generals.Color["white"] + "\n")
        generals.Go("\t" + generals.Color["redBold"]    + "     " + "[*] " + generals.Color["whiteBold"]  + "Modules: " + generals.Color["white"] + generals.Color["blue"] + "%s" % (totalModules) + generals.Color["white"])
        generals.Go("\t" + generals.Color["redBold"]    + "     " + "[*] " + generals.Color["whiteBold"]  + "Version: " + generals.Color["white"] + generals.Color["blue"] + config.versionFramework + generals.Color["white"])
        generals.Go("\t" + generals.Color["yellowBold"] + "     " + "[!] " + generals.Color["whiteBold"]  + "Author: " + generals.Color["white"] + generals.Color["blue"] + config.authorName + generals.Color["blue"] + " (" + generals.Color["yellow"]+ config.authorNick + generals.Color["blue"] + "), " + config.authorTwitter + generals.Color["white"])
        generals.Go("\t" + generals.Color["yellowBold"] + "     " + "[!] " + generals.Color["whiteBold"]  + "Homepage: " + generals.Color["white"] + generals.Color["blue"] + config.homepage + generals.Color["white"] + "\n")
        generals.Go(generals.Color["blue"] + "  " + config.descriptionFramework + generals.Color["white"] + "\n")
 
    # Options of help, of easy use.
    def help(self, nameHelp):
        generals.Go("")
        generals.Go("----------")
        generals.Go("[!" + generals.Color["blueBold"] + " " + nameHelp + " " + generals.Color["white"] + "!]")
        generals.Go("----------")
        generals.Go("")
        generals.Go("These are all the commands that you can run in sack")
        generals.Go("")
        generals.Go("go     : " + generals.Color["blue"] + "load, call or execute a module" + generals.Color["white"])
        generals.Go("list   : " + generals.Color["blue"] + "open the list of all the modules" + generals.Color["white"])
        generals.Go("info   : " + generals.Color["blue"] + "to view information from a module" + generals.Color["white"])
        generals.Go("help   : " + generals.Color["blue"] + "to ask for help" + generals.Color["white"])
        generals.Go("reload : " + generals.Color["blue"] + "restart the console sack" + generals.Color["white"])
        generals.Go("about  : " + generals.Color["blue"] + "information on the creator author and collaborators" + generals.Color["white"])
        generals.Go("clear  : " + generals.Color["blue"] + "to clean the terminal" + generals.Color["white"])
        generals.Go("exit   : " + generals.Color["blue"] + "close or exit from the console sack" + generals.Color["white"])
        generals.Go("")

    # Autocompletion
    # Description: To maintain a clean console with autocompletion, this I help of stackoverflow <3
    # Url: http://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-arbitrary-things-not-int/187660#187660
    def niceShell(text, state):
        matches = [i for i in commands if i.startswith(text)]
        if state < len(matches):
            return matches[state]
        else:
            return None

    # Autocompletion of console (shell sack)
    readline.parse_and_bind("tab:complete")
    readline.set_completer(niceShell)

    # Here we write the shell of sack. Where everything connected to call modules to run the magic
    def shell(self):
        command = None
        self.showList()
        self.header(len(self.listing))
        
        while True:
            try:
                command = raw_input(generals.Color["green"] + config.nameFramework + generals.Color["whiteBold"] + ":~>" + " " + generals.Color["white"]) or "help"
                command = command.split()
                # List modules
                if command[0] == "list" or command[0] == "ls":
                    generals.Go("")
                    generals.Go("---------------------")
                    generals.Go("[>" + generals.Color["blueBold"] + " List of modules " + generals.Color["white"] + "<]")
                    generals.Go("---------------------")
                    generals.Go("")
                    for module in self.listing:
                        try:
                            attribute = generals.ImportModule(self.define + self.point + "%s" % (module))
                        except ImportError:
                            generals.Go(generals.Color["redBold"] + "Alert: " + generals.Color["white"] + "There was a problem to the load the module " + generals.Color["blueBold"] + "\'%s\'" % (module))
                        else:
                            reflectModule = generals.Color["greenBold"] + "[" + generals.Color["blueBold"] + ">" + generals.Color["greenBold"] + "]" + generals.Color["white"] + " %s {%s} - %s" % (module, generals.Color["blue"] + attribute.doVersion + generals.Color["white"], attribute.doDescription)
                            generals.Go(reflectModule)
                    generals.Go("")
                elif command[0] == "go" or command[0] == "GO" or command[0] == "Go":
                    try:
                        preData = command[1]
                    except IndexError:
                        generals.Go(generals.Color["blueBold"] + "Usage:" + generals.Color["white"] + " go [module name] [commands]")
                    else:
                        self.go(command)
                elif command[0] == "exit" or command[0] == "close":
                    self.deleteFilesTarget("index.html", "redirect.html")
                    generals.Go(generals.Color["red"] + "Goodbye: " + generals.Color["white"] +  "Thank you for having me used, I hope soon.")
                    break
                elif command[0] == "clear":
                    generals.Go("\033[H\033[J")
                elif command[0] == "info":
                    try:
                        preData = command[1]
                    except IndexError:
                        generals.Go(generals.Color["blueBold"] + "Usage:" + generals.Color["white"] + " info [module name]")
                    else:
                        self.infoModule(preData)
                elif command[0] == "about":
                    generals.Go("")
                    generals.Go("---------------------------")
                    generals.Go("[>" + generals.Color["blueBold"] + "  Credits " + generals.Color["whiteBold"] + "&" + generals.Color["blueBold"] + " copyright  " + generals.Color["white"] + "<]")
                    generals.Go("---------------------------")
                    generals.Go("")
                    generals.Go(generals.Color["yellowBold"] + "[!] " + generals.Color['white'] + "Creator:" + " " + generals.Color["blue"] + config.authorName + generals.Color["blue"] + " (" + generals.Color["yellow"]+ config.authorNick + generals.Color["blue"] + ")")
                    generals.Go(generals.Color["yellowBold"] + "[!] " + generals.Color['white'] + "Contact:" + " " + generals.Color["blue"] + "email:" + generals.Color["green"] + "*****@*****.**" + generals.Color["white"] + " | " + generals.Color["blue"] + "twitter:" + generals.Color["green"] + "@jofpin" + generals.Color["white"])
                    generals.Go(generals.Color["yellowBold"] + "[!] " + generals.Color['white'] + "Version:" + " " + generals.Color["blue"] + config.versionFramework + generals.Color['white'])
                    generals.Go(generals.Color["yellowBold"] + "[!] " + generals.Color['white'] + "Date:" + " " + generals.Color["blue"] + config.dateFramework + generals.Color['white'])
                    generals.Go("")
                elif command[0] == "reload":
                    self.header(len(self.listing))
                # Notices for the good writing of commands (list, clear, info)
                elif command[0] == "lis" or command[0] == "ist" or command[0] == "l" or command[0] == "lisr" or command[0] == "liss" or command[0] == "sl":
                    generals.Go(generals.Color["yellowBold"] + "Notice: " + generals.Color["white"] + "I think that tried of write " + generals.Color["blueBold"] + "'ls'" + generals.Color["white"] + " or " + generals.Color["blueBold"] + "'list'" + generals.Color["white"] + ", are those commands to see the list of modules.")
                elif command[0] == "cls" or command[0] == "cler" or command[0] == "c" or command[0] == "clean" or command[0] == "cl":
                    generals.Go(generals.Color["yellowBold"] + "Notice: " + generals.Color["white"] + "I think that tried of write " + generals.Color["blueBold"] + "'clear'" + generals.Color["white"] + ", the command to clean the console")
                elif command[0] == "inf" or command[0] == "in" or command[0] == "i" or command[0] == "if" or command[0] == "information":
                    generals.Go(generals.Color["yellowBold"] + "Notice: " + generals.Color["white"] + "I think that tried of write " + generals.Color["blueBold"] + "'info'" + generals.Color["white"] + ", the command to view the information of the modules")
                elif command[0] == "help":
                    self.help("Help")
                else:
                    generals.Go(generals.Color["redBold"] + "Error: " + generals.Color["blue"] +  "\'%s\' " % command[0] + generals.Color["white"] + "not be found the order, write command: " + generals.Color["whiteBold"] + "help" + generals.Color["white"])
            # Prevent closed easier, avoid interruption and continue.        
            except KeyboardInterrupt:
                generals.Go("")
                generals.Go(generals.Color["redBold"] + "Alert: " + generals.Color["white"] + "Interrupted.")
            except Exception as error:
                generals.Go(generals.Color["redBold"] + "Error: " + generals.Color["white"] + "%s" % error)

    # Preview module information
    def infoModule(self, moduleName):
        try:
            attribute = generals.ImportModule(self.define + self.point + "%s" % (moduleName)) 
        except ImportError:
            generals.Go(generals.Color["redBold"] + "Error: " + generals.Color["white"] + "not it can load " + generals.Color["blueBold"] + "\'%s\' " % (moduleName) + generals.Color["white"] + "in sack")
        else:
            try:
                generals.Go("")
                generals.Go(generals.Color["yellowBold"] + "[!]" + generals.Color["white"] + " " + "Information of " + generals.Color["blueBold"] + "%s" % moduleName + generals.Color["white"] + " " + "module")
                generals.Go("")
                generals.Go("name        :" + generals.Color["blue"] + " %s" % moduleName + generals.Color["white"])
                generals.Go("description :" + generals.Color["blue"] + " %s" % attribute.doDescription + generals.Color["white"])
                generals.Go("version     :" + generals.Color["blue"] + " %s" % attribute.doVersion + generals.Color["white"])
                generals.Go("date        :" + generals.Color["blue"] + " %s" % attribute.doDate + generals.Color["white"])
                generals.Go("author      :" + generals.Color["blue"] + " %s" % attribute.doAuthor + generals.Color["white"])
                generals.Go("")
            except IndexError:
                generals.Go(generals.Color["redBold"] + "Error: " + generals.Color["white"] + "set up well all the variables with the prefix (do) for this module.")

    # Configure the reading of those files with the suffix (.py)            
    def showList(self):
        principal = os.getcwd()
        os.chdir(self.path)
        self.modules = glob.glob("*" + self.point + self.suffix)

        # no modules
        if not self.modules:
            generals.Go(generals.Color["yellowBold"] + "Notice: " + generals.Color["white"] + "There are no modules available.")
        else:
            os.chdir(principal)
            for module in self.modules:
                module = module.split(self.point)[0]
                if module == "__init__":
                    continue
                self.listing.append(module)

    # Header design to modules            
    def headerModule(self, nameModule, versionModule, authorModule, copyrightModule):
        generals.Go("")
        generals.Go(generals.Color["greenBold"] + "+" + generals.Color["white"] + "--" + generals.Color["blue"] + "=" + generals.Color["yellowBold"] + "[->" + generals.Color["white"] + " " + nameModule)
        generals.Go(generals.Color["greenBold"] + "+" + generals.Color["white"] + "--" + generals.Color["blue"] + "=" + generals.Color["yellowBold"] + "[->" + generals.Color["white"] + " " + "Version: " + versionModule)
        generals.Go(generals.Color["greenBold"] + "+" + generals.Color["white"] + "--" + generals.Color["blue"] + "=" + generals.Color["yellowBold"] + "[->" + generals.Color["white"] + " " + "Author: " + authorModule)
        generals.Go(generals.Color["greenBold"] + "+" + generals.Color["white"] + "--" + generals.Color["blue"] + "=" + generals.Color["yellowBold"] + "[->" + generals.Color["white"] + " " + "Copyright: " + copyrightModule)
        generals.Go("")
        pass

    # Log Utility           
    def shellLog(self, msg):
        generals.Go("")
        generals.Go(generals.Color["greenBold"] + "+" + generals.Color["white"] + "--" + generals.Color["blue"] + "=" + generals.Color["yellowBold"] + "[->" + generals.Color["white"] + " " + msg) 
        pass

    # Function to delete target files
    def deleteFilesTarget(self, indexFile, redirectFile):
        if os.path.exists(indexFile):
            os.remove(indexFile)
        if os.path.exists(redirectFile):
            os.remove(redirectFile)

    # Add simple options    
    def usageOpt(self, string):
        generals.Go(generals.Color["blue"] + "Usage:" + " " + generals.Color["white"] + string)

    # Add html to file of redirect    
    def generatePost(self, url, urlAction, requestPost):
        # Create the page that will reidrect to the orignal page.

        #redirectFile = "redirect.html"
        #pathRedirect = os.getcwd() + "/data/" + indexFile

        with open("redirect.html", "w") as html:
            html.write("<!doctype html>")
            html.write("\n")
            html.write("<html>")
            html.write("\n")
            html.write("<head>") 
            html.write("\n")
            html.write("\t" + "<title>" + "Redirection.." + "</title>")
            html.write("\n")
            html.write("</head>")
            html.write("\n")
            html.write("<body>")
            html.write("\n")
            html.write("\t" + "<form id=\"sackForm\" action=\"%s\" method=\"post\" >\n" % urlAction)
            for post in requestPost:
                nameParameter = post.split()
                value = post.split()
                html.write("\t\t" + "<input name=\"%s\" value=\"%s\" type=\"hidden\" >\n" % (nameParameter, value))
            html.write("\t" + "</form>")
            html.write("\n")
            html.write("<!-- Submit data Form -->")
            html.write("\n")
            html.write("<!-- Copyright 2016 by Sack -->")
            html.write("\n")
            html.write("<script type=\"text/javascript\">document.forms[\"sackForm\"].submit();</script>")
            html.write("\n")
            html.write("</body>")
            html.write("\n")
            html.write("</html>")
        html.close()
#SERVER FIN

    # Execution of modules
    def go(self, command):
        moduleName = command[1]
        try:
            attribute = generals.ImportModule(self.define + self.point + "%s" % (moduleName))
            attribute.boot(command)
        except ImportError:
            generals.Go(generals.Color["yellowBold"] + "Notice: " + generals.Color["white"] + "no you can run " + generals.Color["blueBold"] + "\'%s\' " % moduleName + generals.Color["white"] + "inside sack; is likely that the module does not exist.")

    # Here we put at stake the shell, which runs the SACK class in the main file (sack.py)        
    def main(self):
        # Detect operating system, to compose the compatibility
        generals.checkOS()
        # Make a call to run the shell console
        framework = sack()
        framework.shell()
Ejemplo n.º 45
0
def question(question,
             typefunc,
             default=None,
             autocomplete=True,
             ranges=False):
    if typefunc == int or typefunc == float:
        if not default == None and not isinstance(default, list):
            print 'Default to int or float question must be list!'
            quit(1)
    if typefunc == str and autocomplete:
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")  # activate autocomplete
    else:
        readline.parse_and_bind("tab: ")  # deactivate autocomplete

    while True:
        s = question
        if default != None:
            if typefunc == bool or typefunc == str:
                s += ' [%s]' % (str(default))
            elif typefunc == int or typefunc == float:
                s += ' ['
                for i in default:
                    s += str(i) + ' '
                s = s[:-1] + ']'
        if typefunc == str and autocomplete:
            s += ' (autocomplete enabled)'
        if typefunc == int and ranges:
            s += ' (range comprehension enabled)'
        s += ' '

        line = raw_input(s)
        line = re.sub('#.*$', '', line).strip()
        if not typefunc == str:
            line = line.lower()

        if line == '' or line == '\n':
            if default != None:
                KEYSTROKES.write(line + ' ' * (40 - len(line)) + ' #' + s +
                                 '\n')
                return default
            else:
                continue

        if typefunc == bool:
            posresponse = [
                'y', 'yes', 'true', 't', 'ja', 'si', 'yea', 'yeah', 'aye',
                'sure', 'definitely'
            ]
            negresponse = ['n', 'no', 'false', 'f', 'nein', 'nope']
            if line in posresponse:
                KEYSTROKES.write(line + ' ' * (40 - len(line)) + ' #' + s +
                                 '\n')
                return True
            elif line in negresponse:
                KEYSTROKES.write(line + ' ' * (40 - len(line)) + ' #' + s +
                                 '\n')
                return False
            else:
                print 'I didn' 't understand you.'
                continue

        if typefunc == str:
            KEYSTROKES.write(line + ' ' * (40 - len(line)) + ' #' + s + '\n')
            return line

        if typefunc == float:
            # float will be returned as a list
            f = line.split()
            try:
                for i in range(len(f)):
                    f[i] = typefunc(f[i])
                KEYSTROKES.write(line + ' ' * (40 - len(line)) + ' #' + s +
                                 '\n')
                return f
            except ValueError:
                print 'Please enter floats!'
                continue

        if typefunc == int:
            # int will be returned as a list
            f = line.split()
            out = []
            try:
                for i in f:
                    if ranges and '~' in i:
                        q = i.split('~')
                        for j in range(int(q[0]), int(q[1]) + 1):
                            out.append(j)
                    else:
                        out.append(int(i))
                KEYSTROKES.write(line + ' ' * (40 - len(line)) + ' #' + s +
                                 '\n')
                return out
            except ValueError:
                if ranges:
                    print 'Please enter integers or ranges of integers (e.g. "-3~-1  2  5~7")!'
                else:
                    print 'Please enter integers!'
                continue
Ejemplo n.º 46
0
            matches = rlcompleter.Completer.attr_matches(self, text)
            if not matches: matches = []
            b = text.find('.')
            try:
                if 0 <= b and self.namespace[text[:b]].__name__ == 'ROOT':
                    matches += self.root_global_matches(
                        text[b + 1:], text[:b + 1])
            except AttributeError:  # not all objects have a __name__
                pass
            return matches

    readline.set_completer(RootNameCompleter().complete)
    readline.set_completer_delims(readline.get_completer_delims().replace(
        os.sep, ''))

    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('set show-all-if-ambiguous On')
except:
    # module readline typically doesn't exist on non-Unix platforms
    pass

## special filter on MacOS X (warnings caused by linking that is still required)
if sys.platform == 'darwin':
    import warnings
    warnings.filterwarnings( action='ignore', category=RuntimeWarning, module='ROOT',\
       message='class \S* already in TClassTable$' )

### load PyROOT C++ extension module, special case for linux and Sun ------------
_root = cppyy._backend

if 'cppyy' in sys.builtin_module_names:
Ejemplo n.º 47
0
Archivo: run.py Proyecto: dmknght/ZSC
def get_command(usr_command):
    backup_commands = usr_command
    crawler = 0
    command_path = ['zsc']
    command = ''
    while True:
        try:
            command = _input('/'.join(command_path), 'any', False)
        except KeyboardInterrupt:
            pass
        except:
            warn('interrupted by user!\nExit\n')
            sys.exit(0)
        check = True

        if command and command.startswith('#'):  # allows for comments
            continue

        inContext = ['clear', 'help', 'about', 'version', 'back']
        for option in usr_command:
            if command == option and command not in inContext:
                crawler += 1
                if crawler == 1:
                    usr_command = usr_command[option][1]
                    command_path.append(option)
                if crawler == 2:
                    if command == 'search':
                        search_shellcode(False, 0)
                        usr_command = backup_commands
                        completer = AutoComplete(usr_command)
                        readline.set_completer(completer.complete)
                        readline.parse_and_bind('tab: complete')
                        crawler = 0
                        command_path = ['zsc']
                    elif command == 'download':
                        download_shellcode(False, 0, '')
                        usr_command = backup_commands
                        completer = AutoComplete(usr_command)
                        readline.set_completer(completer.complete)
                        readline.parse_and_bind('tab: complete')
                        crawler = 0
                        command_path = ['zsc']
                    elif command == 'shell_storm_list':
                        grab_all()
                        usr_command = backup_commands
                        completer = AutoComplete(usr_command)
                        readline.set_completer(completer.complete)
                        readline.parse_and_bind('tab: complete')
                        crawler = 0
                        command_path = ['zsc']
                    elif command == 'generate':
                        usr_command = usr_command[option]
                        command_path.append(option)
                    else:
                        while True:
                            f = []
                            import os as OS
                            for (dirpath, dirnames, filenames) in OS.walk(''):
                                f.extend(filenames)
                                break
                            completer = AutoComplete(f)
                            readline.set_completer(completer.complete)
                            filename = _input('filename', 'any', True)
                            completer = AutoComplete(usr_command)
                            readline.set_completer(completer.complete)
                            try:
                                content = open(filename, 'rb').read()
                                break
                            except:
                                warn('sorry, cann\'t find file\n')
                        usr_command = usr_command[option]
                        command_path.append(option)
                        completer = AutoComplete(usr_command)
                        readline.set_completer(completer.complete)
                        readline.parse_and_bind('tab: complete')
                        t = True
                        while t:
                            encode = _input('encode', 'any', True)
                            for en in usr_command:
                                if encode == en:
                                    t = False
                            if t == True:
                                warn('please enter a valid encode name\n')
                        obf_code(option, encode, filename, content, False)
                        usr_command = backup_commands
                        completer = AutoComplete(usr_command)
                        readline.set_completer(completer.complete)
                        readline.parse_and_bind('tab: complete')
                        crawler = 0
                        command_path = ['zsc']
                if crawler == 3:
                    os = option
                    usr_command = usr_command[option]
                    command_path.append(option)
                if crawler == 4:
                    func = option
                    usr_command = usr_command[option]
                    command_path.append(option)
                if crawler == 5:
                    data = []
                    backup_option = option
                    if option != '':
                        options = option.rsplit('&&')
                        for o in options:
                            data.append(_input(o, 'any', True))
                        n = 0
                        write('\n')
                        for o in options:
                            info('%s set to "%s"\n' % (o, data[n]))
                            n += 1
                    run = getattr(
                        __import__('libs.shellcrafter.%s.%s' % (os, func),
                                   fromlist=['run']), 'run')
                    shellcode = run(data)
                    write('\n')
                    for encode in backup_commands['shellcode'][1]['generate'][
                            os][func][backup_option]:
                        info(encode + '\n')
                    write('\n\n')
                    info('enter encode type\n')
                    completer = AutoComplete(
                        backup_commands['shellcode'][1]['generate'][os][func]
                        [backup_option])
                    readline.set_completer(completer.complete)
                    readline.parse_and_bind('tab: complete')
                    try:
                        encode = _input(
                            '/'.join(command_path) + "/encode_type", 'any',
                            False)
                        # if encode == None:
                        #     _lets_error
                    except:
                        encode = 'none'
                        warn('\n"none" encode selected\n')
                    write('\n')
                    assembly_code_or_not = _input(
                        'Output assembly code?(y or n)', 'any', True)
                    if assembly_code_or_not == 'y':
                        assembly_code = True
                    else:
                        assembly_code = False
                    if assembly_code == True:
                        write('\n' +
                              encode_process(encode, shellcode, os, func) +
                              '\n\n')
                    output_shellcode = _input(
                        'Output shellcode to screen?(y or n)', 'any', True)
                    shellcode_op = op(
                        encode_process(encode, shellcode, os, func), os)
                    if output_shellcode == 'y':
                        info('Generated shellcode is:\n' + shellcode_op +
                             '\n\n')
                    file_or_not = _input(
                        'Shellcode output to a .c file?(y or n)', 'any', True)
                    if file_or_not == 'y':
                        target = _input('Target .c file?', 'any', True)
                        file_output(target, func, data, os, encode, shellcode,
                                    shellcode_op)
                    usr_command = backup_commands
                    completer = AutoComplete(usr_command)
                    readline.set_completer(completer.complete)
                    readline.parse_and_bind('tab: complete')
                    crawler = 0
                    command_path = ['zsc']
                completer = AutoComplete(usr_command)
                readline.set_completer(completer.complete)
                readline.parse_and_bind('tab: complete')
                check = False
        if command == 'exit' or command == 'quit':
            write(color.color('reset'))
            sys.exit('Exit')
        elif command == 'help':
            _help(commands_help)
        # elif command == 'restart':
        #     usr_command = backup_commands
        #     completer = AutoComplete(usr_command)
        #     readline.set_completer(completer.complete)
        #     readline.parse_and_bind('tab: complete')
        #     crawler = 0
        #     command_path = ['zsc']
        # elif command == 'about':
        #     about()
        # elif command == 'version':
        #     version()
        elif command == 'back':
            if len(command_path) > 1:
                command_path.pop()
                usr_command = backup_commands
                for option in command_path:
                    if option == 'zsc':
                        pass
                    elif option == command_path[1]:
                        usr_command = usr_command[option][1]
                    else:
                        usr_command = usr_command[option]
                completer = AutoComplete(usr_command)
                readline.set_completer(completer.complete)
                readline.parse_and_bind('tab: complete')
                crawler -= 1
            else:
                info('Can\'t go back from here!\n')
        else:
            if command != '' and check == True:
                info('Command not found!\n')
Ejemplo n.º 48
0
def interact(mydict=None, argv=None, mybanner=None, loglevel=20):
    global session
    import code, sys, pickle, os, getopt, re
    from .config import conf
    conf.interactive = True
    if loglevel is not None:
        conf.logLevel = loglevel

    the_banner = "Welcome to Scapy (%s)"
    if mybanner is not None:
        the_banner += "\n"
        the_banner += mybanner

    if argv is None:
        argv = sys.argv

    import atexit
    try:
        import rlcompleter, readline
    except ImportError:
        log_loading.info("Can't load Python libreadline or completer")
        READLINE = 0
    else:
        READLINE = 1

        class ScapyCompleter(rlcompleter.Completer):
            def global_matches(self, text):
                matches = []
                n = len(text)
                for lst in [dir(__builtin__), list(session.keys())]:
                    for word in lst:
                        if word[:n] == text and word != "__builtins__":
                            matches.append(word)
                return matches

            def attr_matches(self, text):
                m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
                if not m:
                    return
                expr, attr = m.group(1, 3)
                try:
                    object = eval(expr)
                except:
                    object = eval(expr, session)
                if isinstance(object, Packet) or isinstance(
                        object, Packet_metaclass):
                    words = [x for x in dir(object) if x[0] != "_"]
                    words += [x.name for x in object.fields_desc]
                else:
                    words = dir(object)
                    if hasattr(object, "__class__"):
                        words = words + rlcompleter.get_class_members(
                            object.__class__)
                matches = []
                n = len(attr)
                for word in words:
                    if word[:n] == attr and word != "__builtins__":
                        matches.append("%s.%s" % (expr, word))
                return matches

        readline.set_completer(ScapyCompleter().complete)
        readline.parse_and_bind("C-o: operate-and-get-next")
        readline.parse_and_bind("tab: complete")

    session = None
    session_name = ""
    STARTUP_FILE = DEFAULT_STARTUP_FILE
    PRESTART_FILE = DEFAULT_PRESTART_FILE

    iface = None
    try:
        opts = getopt.getopt(argv[1:], "hs:Cc:Pp:d")
        for opt, parm in opts[0]:
            if opt == "-h":
                _usage()
            elif opt == "-s":
                session_name = parm
            elif opt == "-c":
                STARTUP_FILE = parm
            elif opt == "-C":
                STARTUP_FILE = None
            elif opt == "-p":
                PRESTART_FILE = parm
            elif opt == "-P":
                PRESTART_FILE = None
            elif opt == "-d":
                conf.logLevel = max(1, conf.logLevel - 10)

        if len(opts[1]) > 0:
            raise getopt.GetoptError("Too many parameters : [%s]" %
                                     " ".join(opts[1]))

    except getopt.GetoptError as msg:
        log_loading.error(msg)
        sys.exit(1)

    if PRESTART_FILE:
        _read_config_file(PRESTART_FILE)

    scapy_builtins = __import__("all", globals(), locals(), ".").__dict__
    builtins.__dict__.update(scapy_builtins)
    globkeys = list(scapy_builtins.keys())
    globkeys.append("scapy_session")
    scapy_builtins = None  # XXX replace with "with" statement
    if mydict is not None:
        builtins.__dict__.update(mydict)
        globkeys += list(mydict.keys())

    conf.color_theme = DefaultTheme()
    if STARTUP_FILE:
        _read_config_file(STARTUP_FILE)

    if session_name:
        try:
            os.stat(session_name)
        except OSError:
            log_loading.info("New session [%s]" % session_name)
        else:
            try:
                try:
                    session = pickle.load(gzip.open(session_name, "rb"))
                except IOError:
                    session = pickle.load(open(session_name, "rb"))
                log_loading.info("Using session [%s]" % session_name)
            except EOFError:
                log_loading.error("Error opening session [%s]" % session_name)
            except AttributeError:
                log_loading.error(
                    "Error opening session [%s]. Attribute missing" %
                    session_name)

        if session:
            if "conf" in session:
                conf.configure(session["conf"])
                session["conf"] = conf
        else:
            conf.session = session_name
            session = {"conf": conf}

    else:
        session = {"conf": conf}

    builtins.__dict__["scapy_session"] = session

    if READLINE:
        if conf.histfile:
            try:
                readline.read_history_file(conf.histfile)
            except IOError:
                pass
        atexit.register(scapy_write_history_file, readline)

    atexit.register(scapy_delete_temp_files)

    IPYTHON = False
    if conf.interactive_shell.lower() == "ipython":
        try:
            import IPython
            IPYTHON = True
        except ImportError as e:
            log_loading.warning(
                "IPython not available. Using standard Python shell instead.")
            IPYTHON = False

    if IPYTHON:
        banner = the_banner % (
            conf.version) + " using IPython %s" % IPython.__version__

        # Old way to embed IPython kept for backward compatibility
        try:
            args = ['']  # IPython command line args (will be seen as sys.argv)
            ipshell = IPython.Shell.IPShellEmbed(args, banner=banner)
            ipshell(local_ns=session)
        except AttributeError as e:
            pass

        # In the IPython cookbook, see 'Updating-code-for-use-with-IPython-0.11-and-later'
        IPython.embed(user_ns=session, banner2=banner)

    else:
        code.interact(banner=the_banner % (conf.version),
                      local=session,
                      readfunc=conf.readfunc)

    if conf.session:
        save_session(conf.session, session)

    for k in globkeys:
        try:
            del (builtins.__dict__[k])
        except:
            pass
Ejemplo n.º 49
0
def query(question, values, default=None, list_values = False, ignorecase = True ):
    """Preset a few options
    
    The question argument is a string, nothing magical.
    
    The values argument accepts input in two different forms. The simpler form
    (a tuple with strings) looks like:
    
        .. code-block:: Python
        
            ('Male','Female')
    
    And it will pop up a question asking the user for a gender and requiring
    the user to enter either 'male' or 'female' (case doesn't matter unless
    you set the third arguement to false).
    The other form is something like:
    
        .. code-block:: Python
        
            ({'values':('Male','M'),'fg':'cyan'},
            {'values':('Female','F'),'fg':'magenta'})
    
    This will pop up a question with Male/Female (each with appropriate
    colouring). Additionally, if the user types in just 'M', it will be
    treated as if 'Male' was typed in. The first item in the 'values' tuple
    is treated as default and is the one that is returned by the function
    if the user chooses one in that group.
    In addition the function can handle non-string objects quite fine. It
    simple displays the output object.__str__() and compares the user's input
    against that. So the the code
    
        .. code-block:: Python
        
            query("Python rocks? ",(True, False))
    
    will return a bool (True) when the user types in the string 'True' (Of
    course there isn't any other reasonable answer than True anyways :P)
    
    ``default`` is the value function returns if the user types nothing in. This is
    can be used to cancel the input so-to-speek
    
    Using list_values = False will display a list, with descriptions printed out
    from the 'desc' keyword
    """
    values = list(values)
    for i in range(len(values)):
        if not isinstance(values[i], dict):
            values[i] = {'values': [values[i]]}
    try:
        import readline, rlcomplete
        wordlist = [ str(v) for value in values
                    for v in value['values']]
        completer = rlcomplete.ListCompleter(wordlist, ignorecase)
        readline.parse_and_bind("tab: complete")
        readline.set_completer(completer.complete)
    except ImportError:
        pass
    valuelist = []
    for item in values:
        entry = ( display('bright', item.get('fg'), item.get('bg')) +
            str(item['values'][0]) + display(['default']) )
        if str(item['values'][0]) == str(default): entry = '['+entry+']'
        if list_values: entry += ' : ' + item['desc']
        valuelist.append(entry)
    if list_values: question += os.linesep + os.linesep.join(valuelist) + os.linesep
    else: question += ' (' + '/'.join(valuelist) + ')'
    return input_object(question, cast = query_cast, default=default,
                 castarg=[values,ignorecase])
Ejemplo n.º 50
0
def eb_injection_handler(url, delay, filename, http_request_method):

    counter = 1
    vp_flag = True
    no_result = True
    export_injection_info = False
    injection_type = "Results-based Command Injection"
    technique = "eval-based code injection technique"

    for item in range(0, len(settings.EXECUTION_FUNCTIONS)):
        settings.EXECUTION_FUNCTIONS[
            item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "("
    settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS

    url = eb_injector.warning_detection(url, http_request_method)

    sys.stdout.write("(*) Testing the " + technique + "... ")
    sys.stdout.flush()

    i = 0
    # Calculate all possible combinations
    total = len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(
        settings.EVAL_SUFFIXES)

    for prefix in settings.EVAL_PREFIXES:
        for suffix in settings.EVAL_SUFFIXES:
            for separator in settings.EVAL_SEPARATORS:
                i = i + 1

                # Check for bad combination of prefix and separator
                combination = prefix + separator
                if combination in settings.JUNK_COMBINATION:
                    prefix = ""

                # Change TAG on every request to prevent false-positive results.
                TAG = ''.join(
                    random.choice(string.ascii_uppercase) for i in range(6))

                randv1 = random.randrange(100)
                randv2 = random.randrange(100)
                randvcalc = randv1 + randv2

                # Define alter shell
                alter_shell = menu.options.alter_shell

                try:
                    if alter_shell:
                        # Classic -alter shell- decision payload (check if host is vulnerable).
                        payload = eb_payloads.decision_alter_shell(
                            separator, TAG, randv1, randv2)
                    else:
                        # Classic decision payload (check if host is vulnerable).
                        payload = eb_payloads.decision(separator, TAG, randv1,
                                                       randv2)

                    suffix = urllib.quote(suffix)
                    # Fix prefixes / suffixes
                    payload = parameters.prefixes(payload, prefix)
                    payload = parameters.suffixes(payload, suffix)
                    # Fixation for specific payload.
                    if ")%3B" + urllib.quote(")}") in payload:
                        payload = payload.replace(")%3B" + urllib.quote(")}"),
                                                  ")" + urllib.quote(")}"))
                    payload = payload + "" + TAG + ""

                    if menu.options.base64:
                        payload = urllib.unquote(payload)
                        payload = base64.b64encode(payload)
                    else:
                        payload = re.sub(" ", "%20", payload)

                    # Check if defined "--verbose" option.
                    if menu.options.verbose:
                        sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " +
                                         payload + Style.RESET_ALL)

                    # Cookie Injection
                    if settings.COOKIE_INJECTION == True:
                        # Check if target host is vulnerable to cookie injection.
                        vuln_parameter = parameters.specify_cookie_parameter(
                            menu.options.cookie)
                        response = eb_injector.cookie_injection_test(
                            url, vuln_parameter, payload)

                    # User-Agent Injection
                    elif settings.USER_AGENT_INJECTION == True:
                        # Check if target host is vulnerable to user-agent injection.
                        vuln_parameter = parameters.specify_user_agent_parameter(
                            menu.options.agent)
                        response = eb_injector.user_agent_injection_test(
                            url, vuln_parameter, payload)

                    # Referer Injection
                    elif settings.REFERER_INJECTION == True:
                        # Check if target host is vulnerable to referer injection.
                        vuln_parameter = parameters.specify_referer_parameter(
                            menu.options.referer)
                        response = eb_injector.referer_injection_test(
                            url, vuln_parameter, payload)

                    else:
                        found_cookie_injection = False
                        # Check if target host is vulnerable.
                        response, vuln_parameter = eb_injector.injection_test(
                            payload, http_request_method, url)

                    # if need page reload
                    if menu.options.url_reload:
                        time.sleep(delay)
                        response = urllib.urlopen(url)

                    # Evaluate test results.
                    shell = eb_injector.injection_test_results(
                        response, TAG, randvcalc)

                    if not menu.options.verbose:
                        percent = ((i * 100) / total)
                        float_percent = "{0:.1f}".format(
                            round(((i * 100) / (total * 1.0)), 2))

                        if shell == False:
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... " + "[ " + float_percent +
                                             "%" + " ]")
                            sys.stdout.flush()

                        if percent == 100:
                            if no_result == True:
                                percent = Fore.RED + "FAILED" + Style.RESET_ALL
                            else:
                                percent = str(float_percent) + "%"
                        elif len(shell) != 0:
                            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                        else:
                            percent = str(float_percent) + "%"

                        sys.stdout.write("\r(*) Testing the " + technique +
                                         "... " + "[ " + percent + " ]")
                        sys.stdout.flush()

                except KeyboardInterrupt:
                    raise

                except SystemExit:
                    raise

                except:
                    continue

                # Yaw, got shellz!
                # Do some magic tricks!
                if shell:
                    found = True
                    no_result = False

                    if settings.COOKIE_INJECTION == True:
                        header_name = " Cookie"
                        found_vuln_parameter = vuln_parameter
                        the_type = " HTTP header"

                    elif settings.USER_AGENT_INJECTION == True:
                        header_name = " User-Agent"
                        found_vuln_parameter = ""
                        the_type = " HTTP header"

                    elif settings.REFERER_INJECTION == True:
                        header_name = " Referer"
                        found_vuln_parameter = ""
                        the_type = " HTTP header"

                    else:
                        header_name = ""
                        the_type = " parameter"
                        if http_request_method == "GET":
                            found_vuln_parameter = parameters.vuln_GET_param(
                                url)
                        else:
                            found_vuln_parameter = vuln_parameter

                    if len(found_vuln_parameter) != 0:
                        found_vuln_parameter = " '" + Style.UNDERLINE + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'"

                    # Print the findings to log file.
                    if export_injection_info == False:
                        export_injection_info = logs.add_type_and_technique(
                            export_injection_info, filename, injection_type,
                            technique)
                    if vp_flag == True:
                        vp_flag = logs.add_parameter(vp_flag, filename,
                                                     http_request_method,
                                                     vuln_parameter, payload)
                    logs.update_payload(filename, counter, payload)
                    counter = counter + 1

                    # Print the findings to terminal.
                    print Style.BRIGHT + "\n(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                    print "  (+) Type : " + Fore.YELLOW + Style.BRIGHT + injection_type + Style.RESET_ALL + ""
                    print "  (+) Technique : " + Fore.YELLOW + Style.BRIGHT + technique.title(
                    ) + Style.RESET_ALL + ""
                    print "  (+) Payload : " + Fore.YELLOW + Style.BRIGHT + re.sub(
                        "%20", " ", payload) + Style.RESET_ALL

                    # Check for any enumeration options.
                    if settings.ENUMERATION_DONE == True:
                        while True:
                            enumerate_again = raw_input(
                                "\n(?) Do you want to enumerate again? [Y/n/q] > "
                            ).lower()
                            if enumerate_again in settings.CHOISE_YES:
                                eb_enumeration.do_check(
                                    separator, TAG, prefix, suffix,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename)
                                break
                            elif enumerate_again in settings.CHOISE_NO:
                                break
                            elif enumerate_again in settings.CHOISE_QUIT:
                                sys.exit(0)
                            else:
                                if enumerate_again == "":
                                    enumerate_again = "enter"
                                print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                                pass

                    else:
                        eb_enumeration.do_check(separator, TAG, prefix, suffix,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell,
                                                filename)

                    # Check for any system file access options.
                    if settings.FILE_ACCESS_DONE == True:
                        while True:
                            file_access_again = raw_input(
                                "(?) Do you want to access files again? [Y/n/q] > "
                            ).lower()
                            if file_access_again in settings.CHOISE_YES:
                                if not menu.options.verbose:
                                    print ""
                                eb_file_access.do_check(
                                    separator, TAG, prefix, suffix,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename)
                                break
                            elif file_access_again in settings.CHOISE_NO:
                                break
                            elif file_access_again in settings.CHOISE_QUIT:
                                sys.exit(0)
                            else:
                                if file_access_again == "":
                                    file_access_again = "enter"
                                print Back.RED + "(x) Error: '" + file_access_again + "' is not a valid answer." + Style.RESET_ALL
                                pass
                    else:
                        eb_file_access.do_check(separator, TAG, prefix, suffix,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell,
                                                filename)

                    # Check if defined single cmd.
                    if menu.options.os_cmd:
                        eb_enumeration.single_os_cmd_exec(
                            separator, TAG, prefix, suffix,
                            http_request_method, url, vuln_parameter,
                            alter_shell, filename)

                    # Pseudo-Terminal shell
                    go_back = False
                    go_back_again = False
                    while True:
                        if go_back == True:
                            break
                        gotshell = raw_input(
                            "(?) Do you want a Pseudo-Terminal? [Y/n/q] > "
                        ).lower()
                        if gotshell in settings.CHOISE_YES:
                            print ""
                            print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)"
                            if readline_error:
                                checks.no_readline_module()
                            while True:
                                try:
                                    # Tab compliter
                                    if not readline_error:
                                        readline.set_completer(
                                            menu.tab_completer)
                                        # MacOSX tab compliter
                                        if getattr(
                                                readline, '__doc__', ''
                                        ) is not None and 'libedit' in getattr(
                                                readline, '__doc__', ''):
                                            readline.parse_and_bind(
                                                "bind ^I rl_complete")
                                        # Unix tab compliter
                                        else:
                                            readline.parse_and_bind(
                                                "tab: complete")
                                    cmd = raw_input("""commix(""" +
                                                    Style.BRIGHT + Fore.RED +
                                                    """os_shell""" +
                                                    Style.RESET_ALL +
                                                    """) > """)
                                    cmd = checks.escaped_cmd(cmd)
                                    if cmd.lower() in settings.SHELL_OPTIONS:
                                        os_shell_option = checks.check_os_shell_options(
                                            cmd.lower(), technique, go_back,
                                            no_result)
                                        if os_shell_option == False:
                                            if no_result == True:
                                                return False
                                            else:
                                                return True
                                        elif os_shell_option == "quit":
                                            sys.exit(0)
                                        elif os_shell_option == "back":
                                            go_back = True
                                            break
                                        elif os_shell_option == "os_shell":
                                            print Fore.YELLOW + "(^) Warning: You are already into an 'os_shell' mode." + Style.RESET_ALL + "\n"
                                        elif os_shell_option == "reverse_tcp":
                                            settings.REVERSE_TCP = True
                                            # Set up LHOST / LPORT for The reverse TCP connection.
                                            lhost, lport = reverse_tcp.configure_reverse_tcp(
                                            )
                                            while True:
                                                if lhost and lport in settings.SHELL_OPTIONS:
                                                    result = checks.check_reverse_tcp_options(
                                                        lhost)
                                                else:
                                                    cmd = reverse_tcp.reverse_tcp_options(
                                                        lhost, lport)
                                                    result = checks.check_reverse_tcp_options(
                                                        cmd)
                                                if result != None:
                                                    if result == 0:
                                                        return False
                                                    elif result == 1 or result == 2:
                                                        settings.REVERSE_TCP = False
                                                        go_back_again = True
                                                        break
                                                # Command execution results.
                                                response = eb_injector.injection(
                                                    separator, TAG, cmd,
                                                    prefix, suffix,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    alter_shell, filename)
                                                # Evaluate injection results.
                                                shell = eb_injector.injection_results(
                                                    response, TAG)
                                                print shell
                                                if menu.options.verbose:
                                                    print ""
                                                print Back.RED + "(x) Error: The reverse TCP connection has been failed!" + Style.RESET_ALL
                                        else:
                                            pass

                                    else:
                                        # The main command injection exploitation.
                                        response = eb_injector.injection(
                                            separator, TAG, cmd, prefix,
                                            suffix, http_request_method, url,
                                            vuln_parameter, alter_shell,
                                            filename)

                                        # if need page reload
                                        if menu.options.url_reload:
                                            time.sleep(delay)
                                            response = urllib.urlopen(url)

                                        # Command execution results.
                                        shell = eb_injector.injection_results(
                                            response, TAG)
                                        if shell:
                                            shell = "".join(
                                                str(p) for p in shell).replace(
                                                    " ", "", 1)[:-1]
                                            if shell != "":
                                                print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                                            else:
                                                print Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"

                                except KeyboardInterrupt:
                                    raise

                                except SystemExit:
                                    raise

                        elif gotshell in settings.CHOISE_NO:
                            if checks.next_attack_vector(technique,
                                                         go_back) == True:
                                break
                            else:
                                if no_result == True:
                                    return False
                                else:
                                    return True

                        elif gotshell in settings.CHOISE_QUIT:
                            sys.exit(0)

                        else:
                            if gotshell == "":
                                gotshell = "enter"
                            print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                            pass

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Ejemplo n.º 51
0
def main():
    readline.parse_and_bind('tab: complete')
    sesh_file = os.getcwd() + "/" + sys.argv[0]
    sesh_loop()
Ejemplo n.º 52
0
Archivo: run.py Proyecto: dmknght/ZSC
def engine(usr_commands):
    """ engine function"""
    completer = AutoComplete(usr_commands)
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')
    get_command(usr_commands)
Ejemplo n.º 53
0
import subprocess
import cmd
import os
import sys
import platform
import readline
import logging
import rlcompleter
import time
import frida

if 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind -e")
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")

RED = "\033[1;31m"
BLUE = "\033[1;34m"
CYAN = "\033[1;36m"
WHITE = "\033[1;37m"
YELLOW = "\033[1;33m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD = "\033[;1m"
REVERSE = "\033[;7m"
current_dir = os.getcwd()


class parser(cmd.Cmd):
Ejemplo n.º 54
0
            rest_call('PATCH', 'issues/%s' % (number), {'state': 'closed'})


import signal


def signal_handler(signal, frame):
    print 'You pressed Ctrl+C!'
    import sys
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)

import readline
readline.parse_and_bind("tab: complete")
readline.parse_and_bind("set show-all-if-ambiguous on")


class Completer:
    def __init__(self, words):
        self.words = words
        self.prefix = None

    def complete(self, prefix, index):
        if prefix != self.prefix:
            self.matching_words = [
                w for w in self.words if w.startswith(prefix)
            ]
            self.prefix = prefix
        else:
Ejemplo n.º 55
0
def input_cmd(http_request_method, url, vuln_parameter, ip_src, technique):

    err_msg = ""
    if menu.enumeration_options():
        err_msg += "enumeration"
    if menu.file_access_options():
        if err_msg != "":
            err_msg = err_msg + " and "
        err_msg = err_msg + "file-access"

    if err_msg != "":
        warn_msg = "The " + err_msg + " options are not supported "
        warn_msg += "by this module because of the structure of the exfiltrated data. "
        warn_msg += "Please try using any unix-like commands manually."
        print settings.print_warning_msg(warn_msg)

    # Pseudo-Terminal shell
    go_back = False
    go_back_again = False
    while True:
        if go_back == True:
            break
        if not menu.options.batch:
            question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > "
            sys.stdout.write(settings.print_question_msg(question_msg))
            gotshell = sys.stdin.readline().replace("\n", "").lower()
        else:
            gotshell = ""
        if len(gotshell) == 0:
            gotshell = "y"
        if gotshell in settings.CHOICE_YES:
            print "\nPseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)"
            if readline_error:
                checks.no_readline_module()
            while True:
                try:
                    # Tab compliter
                    if not readline_error:
                        readline.set_completer(menu.tab_completer)
                        # MacOSX tab compliter
                        if getattr(readline, '__doc__',
                                   '') is not None and 'libedit' in getattr(
                                       readline, '__doc__', ''):
                            readline.parse_and_bind("bind ^I rl_complete")
                        # Unix tab compliter
                        else:
                            readline.parse_and_bind("tab: complete")
                    cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED +
                                    """os_shell""" + Style.RESET_ALL +
                                    """) > """)
                    cmd = checks.escaped_cmd(cmd)
                    if cmd.lower() in settings.SHELL_OPTIONS:
                        if cmd.lower() == "quit" or cmd.lower() == "back":
                            print ""
                            os._exit(0)
                        elif cmd.lower() == "?":
                            menu.os_shell_options()
                        elif cmd.lower() == "os_shell":
                            warn_msg = "You are already into the '" + cmd.lower(
                            ) + "' mode."
                            print settings.print_warning_msg(warn_msg) + "\n"
                        elif cmd.lower() == "reverse_tcp":
                            warn_msg = "This option is not supported by this module."
                            print settings.print_warning_msg(warn_msg) + "\n"
                    else:
                        # Command execution results.
                        cmd_exec(http_request_method, cmd, url, vuln_parameter,
                                 ip_src)
                except KeyboardInterrupt:
                    os._exit(1)
                except:
                    print ""
                    os._exit(0)
        elif gotshell in settings.CHOICE_NO:
            print ""
            os._exit(0)
        elif gotshell in settings.CHOICE_QUIT:
            print ""
            os._exit(0)
        else:
            err_msg = "'" + gotshell + "' is not a valid answer."
            print settings.print_error_msg(err_msg)
            pass
Ejemplo n.º 56
0
    def __generate_ePass(self):
        """Generate the MF and SAM of an ICAO passport. This method is
        responsible for generating the filesystem and filling it with content.
        Therefore it must interact with the user by prompting for the MRZ and
        optionally for the path to a photo."""
        from PIL import Image
        from virtualsmartcard.cards.ePass import PassportSAM

        # TODO: Sanity checks
        MRZ = raw_input("Please enter the MRZ as one string: ")

        readline.set_completer_delims("")
        readline.parse_and_bind("tab: complete")

        picturepath = raw_input("Please enter the path to an image: ")
        picturepath = picturepath.strip()

        # MRZ1 = "P<UTOERIKSSON<<ANNA<MARIX<<<<<<<<<<<<<<<<<<<"
        # MRZ2 = "L898902C<3UTO6908061F9406236ZE184226B<<<<<14"
        # MRZ = MRZ1 + MRZ2

        try:
            im = Image.open(picturepath)
            pic_width, pic_height = im.size
            fd = open(picturepath, "rb")
            picture = fd.read()
            fd.close()
        except IOError:
            logging.warning("Failed to open file: " + picturepath)
            pic_width = 0
            pic_height = 0
            picture = None

        mf = MF()

        # We need a MF with Application DF \xa0\x00\x00\x02G\x10\x01
        df = DF(parent=mf, fid=4, dfname='\xa0\x00\x00\x02G\x10\x01',
                bertlv_data=[])

        # EF.COM
        COM = pack([(0x5F01, 4, "0107"), (0x5F36, 6, "040000"),
                    (0x5C, 2, "6175")])
        COM = pack(((0x60, len(COM), COM),))
        df.append(TransparentStructureEF(parent=df, fid=0x011E,
                  filedescriptor=0, data=COM))

        # EF.DG1
        DG1 = pack([(0x5F1F, len(MRZ), MRZ)])
        DG1 = pack([(0x61, len(DG1), DG1)])
        df.append(TransparentStructureEF(parent=df, fid=0x0101,
                  filedescriptor=0, data=DG1))

        # EF.DG2
        if picture is not None:
            IIB = "\x00\x01" + inttostring(pic_width, 2) +\
                    inttostring(pic_height, 2) + 6 * "\x00"
            length = 32 + len(picture)  # 32 is the length of IIB + FIB
            FIB = inttostring(length, 4) + 16 * "\x00"
            FRH = "FAC" + "\x00" + "010" + "\x00" +\
                  inttostring(14 + length, 4) + inttostring(1, 2)
            picture = FRH + FIB + IIB + picture
            DG2 = pack([(0xA1, 8, "\x87\x02\x01\x01\x88\x02\x05\x01"),
                       (0x5F2E, len(picture), picture)])
            DG2 = pack([(0x02, 1, "\x01"), (0x7F60, len(DG2), DG2)])
            DG2 = pack([(0x7F61, len(DG2), DG2)])
        else:
            DG2 = ""
        df.append(TransparentStructureEF(parent=df, fid=0x0102,
                  filedescriptor=0, data=DG2))

        # EF.SOD
        df.append(TransparentStructureEF(parent=df, fid=0x010D,
                  filedescriptor=0, data=""))

        mf.append(df)

        self.mf = mf
        self.sam = PassportSAM(self.mf)
Ejemplo n.º 57
0
 def _setup_completer(self) -> None:
     readline.set_completer(self._complete)
     readline.set_completer_delims(" \t\n;")
     readline.parse_and_bind(
         "bind ^I rl_complete" if is_libedit() else "tab: complete")
Ejemplo n.º 58
0
#!/usr/bin/python2
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2014 IBM Corporation
# Copyright 2015-2016 Lenovo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import readline
import socket

connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.connection.connect('/var/run/confluent/dbg.sock')

readline.parse_and_bind("tab: complete")
readline.parse_and_bind("set bell-style none")

Ejemplo n.º 59
0
    def start(self, argv):
        # Install signal handlers
        _prev_signals = {}
        if _thread_name() == '_MainThread':
            for s in (signal.SIGTERM, signal.SIGINT):
                _prev_signals[s] = signal.getsignal(s)
                signal.signal(s, self.__sigTERMhandler)
        try:
            # Command line options
            if self._argv is None:
                ret = self.initCmdLine(argv)
                if ret is not None:
                    if ret:
                        return True
                    raise ServerExecutionException(
                        "Init of command line failed")

            # Commands
            args = self._args

            # Interactive mode
            if self._conf.get("interactive", False):
                try:
                    import readline
                except ImportError:
                    raise ServerExecutionException("Readline not available")
                try:
                    ret = True
                    if len(args) > 0:
                        ret = self.__processCommand(args)
                    if ret:
                        readline.parse_and_bind("tab: complete")
                        self.dispInteractive()
                        while True:
                            cmd = input_command()
                            if cmd == "exit" or cmd == "quit":
                                # Exit
                                return True
                            if cmd == "help":
                                self.dispUsage()
                            elif not cmd == "":
                                try:
                                    self.__processCommand(shlex.split(cmd))
                                except Exception as e:  # pragma: no cover
                                    if self._conf["verbose"] > 1:
                                        logSys.exception(e)
                                    else:
                                        logSys.error(e)
                except (EOFError, KeyboardInterrupt):  # pragma: no cover
                    output("")
                    raise
            # Single command mode
            else:
                if len(args) < 1:
                    self.dispUsage()
                    return False
                return self.__processCommand(args)
        except Exception as e:
            if self._conf["verbose"] > 1:
                logSys.exception(e)
            else:
                logSys.error(e)
            return False
        finally:
            self._alive = False
            for s, sh in _prev_signals.iteritems():
                signal.signal(s, sh)
Ejemplo n.º 60
0
def interactive_browser(cfg, srcdir=None):
    """
    launch an interactive view for browsing the original
    archives.

    TODO: Enhance functionality and fix SLP conversion.
    """

    info("launching interactive data browser...")

    # the variables are actually used, in the interactive prompt.
    # pylint: disable=possibly-unused-variable

    # Initialize game versions data

    auxiliary_files_dir = cfg / "converter" / "games"
    avail_game_eds, avail_game_exps = create_version_objects(auxiliary_files_dir)

    # Acquire game version info
    game_version = get_game_version(srcdir, avail_game_eds, avail_game_exps)
    data = mount_asset_dirs(srcdir, game_version)

    if not data:
        warn("cannot launch browser as no valid input assets were found.")
        return

    def save(path, target):
        """
        save a path to a custom target
        """
        with path.open("rb") as infile:
            with open(target, "rb") as outfile:
                outfile.write(infile.read())

    def save_slp(path, target, palette=None):
        """
        save a slp as png.
        """
        from ..entity_object.export.texture import Texture
        from ..value_object.read.media.slp import SLP
        from ..service.read.palette import get_palettes

        if not palette:
            palette = get_palettes(data, game_version)

        with path.open("rb") as slpfile:
            tex = Texture(SLP(slpfile.read()), palette)

            out_path, filename = os.path.split(target)
            tex.save(Directory(out_path).root, filename)

    import code
    from pprint import pprint

    import rlcompleter

    completer = rlcompleter.Completer(locals())
    readline.parse_and_bind("tab: complete")
    readline.parse_and_bind("set show-all-if-ambiguous on")
    readline.set_completer(completer.complete)

    code.interact(
        banner=("\nuse `pprint` for beautiful output!\n"
                "you can access stuff by the `data` variable!\n"
                "`data` is an openage.util.fslike.path.Path!\n\n"
                "* version detection:   pprint(game_versions)\n"
                "* list contents:       pprint(list(data['graphics'].list()))\n"
                "* dump data:           save(data['file/path'], '/tmp/outputfile')\n"
                "* save a slp as png:   save_slp(data['dir/123.slp'], '/tmp/pic.png')\n"),
        local=locals()
    )