def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - long(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print "CloudMonkey history cleared"
         return
     elif len(historyArg) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(long(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in xrange(startIdx, endIdx):
         self.monkeyprint("%s %s" % (str(idx).rjust(numLen),
                                     readline.get_history_item(idx)))
Example #2
0
    def history(start=None, end=None, lines=30,
                   number=False):
        """
        Display the history starting from entry 'start' to
        entry 'end'. Only available on platforms where the
        readline module can be imported.

        History starts from 0 and goes to a large number.
        The history file is $ZENHOME/.pyhistory by default.

        @parameter start: Line number to start printing
        @type start: integer
        @parameter end: Line number to finish printing
        @type end: integer
        @parameter lines: number of lines to show if no end
        @type lines: integer
        @parameter number: show the line numbers?
        @type number: boolean
        """
        if readline is not None:
            maxHistLength = readline.get_current_history_length()
            if start is None:
                start = maxHistLength
            if end is None:
                end = maxHistLength - lines
            if start < end:
                end, start = start, end
            for i in range(end, start):
                if number:
                    print i, readline.get_history_item(i)
                else:
                    print readline.get_history_item(i)
 def do_history(self, args):
     """
     Prints cloudmonkey history
     """
     if self.pipe_runner("history " + args):
         return
     startIdx = 1
     endIdx = readline.get_current_history_length()
     numLen = len(str(endIdx))
     historyArg = args.split(' ')[0]
     if historyArg.isdigit():
         startIdx = endIdx - long(historyArg)
         if startIdx < 1:
             startIdx = 1
     elif historyArg == "clear" or historyArg == "c":
         readline.clear_history()
         print "CloudMonkey history cleared"
         return
     elif len(historyArg
              ) > 1 and historyArg[0] == "!" and historyArg[1:].isdigit():
         command = readline.get_history_item(long(historyArg[1:]))
         readline.set_startup_hook(lambda: readline.insert_text(command))
         self.hook_count = 1
         return
     for idx in xrange(startIdx, endIdx):
         self.monkeyprint(
             "%s %s" %
             (str(idx).rjust(numLen), readline.get_history_item(idx)))
Example #4
0
def printf(x):
    current_line = inspect.currentframe().f_back.f_lineno
    filename = os.path.abspath(sys.argv[0])  #__file__)
    #print('==> ' + str(current_line))
    #print('==> ' + str(filename))

    # Detect if user is using an interactive shell
    if os.isatty(sys.stdout.fileno()):
        first_line = readline.get_current_history_length()
        readline.get_history_item(first_line + 0)  #TODO: find current_line
        print()  #TODO
        return

    with open(filename, 'r') as source:
        for n, line in enumerate(source, start=1):
            if n == current_line:
                #print('==> ' + str(line))

                mo = __import__('re').search(
                    r'printf\s*\(\s*([_a-zA-Z][_a-zA-Z0-9]*)\s*\)', line)
                if mo is not None:
                    print('{}: {}'.format(mo.group(1), x))
                '''
				else:
					print('Error: Steven\'s regex is broken')
				'''

                break

        else:
            print('Error: symbol not found')
Example #5
0
    def eventFilter(self, source, event):

        # Console Input
        if source is self.ui.console_input:
            if event.type() == QEvent.KeyPress:
                if event.key() in (Qt.Key_Enter, Qt.Key_Return):
                    command = self.ui.console_input.text()
                    if command != "":
                        readline.add_history(command)
                    self.length = readline.get_current_history_length()
                    self.index = -1

                if event.key() == Qt.Key_Up:
                    if self.index < self.length:
                        self.index += 1
                        command = readline.get_history_item(self.length -
                                                            self.index)
                        self.ui.console_input.setText(command)

                if event.key() == Qt.Key_Down:
                    if self.index > 0:
                        self.index -= 1
                        command = readline.get_history_item(self.length -
                                                            self.index)

                        self.ui.console_input.setText(command)

            return False
        return False
Example #6
0
 def journal(idx = None):
     if idx != None:
         cache_list = '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())]).split('\n')[int(idx)]
         out = tabulate({"Command": cache_list.split('\n')}, headers=["Command"])
     else:
         cache_list = '\n'.join([str(readline.get_history_item(i + 1)) for i in range(readline.get_current_history_length())])
         out = tabulate({"Command": cache_list.split('\n')}, headers=["Index","Command"], showindex="always")
     print('journal:', out)
Example #7
0
	def repeat_last_cmd(self):
		""" repeat previously typed cmd """
		index = readline.get_current_history_length()
		line = readline.get_history_item(index - 1)
		while self._is_custom_cmd(line):
			index -= 1
			line = readline.get_history_item(index)
		self.push(line)
		return ''
Example #8
0
def main():
	prevrun = []
	warning = 0
	readline.parse_and_bind('tab: complete') # Enable local file tab completion and history
	#readline.read_history_file(history.his)
	# Need to initialize history file here TODO

	while True:
		try:
			dir = os.getcwd()
			input = raw_input('{} >> '.format(dir)) # Print >>, take user input (blocking)
			args = shlex.split(input) # Use shell lexer module to parse input into list of strings
			if input[0][0] == '!':
				if int(input[1][0]) > int(readline.get_current_history_length()):
					continue

				if readline.get_history_item(int(input[1][0])) is not None:
					args = shlex.split(readline.get_history_item(int(input[1][0])))

				if int(input[1][0]) == 0:
					args = prevrun
	
			run = builtins.get(args[0], builtin_exec) # Store relevant function into run variable (builtin_exec being default) 
			retVal = run(args) # Execute function stored in run with arguments args, storing the return value in retVal
			prevrun = args
			if warning > 0:
				warning = warning - 1 # This is a bit silly
			builtin_check_children()

		
		except KeyboardInterrupt: # Can use Finally to run commands regardless, or else to run things when no exception
			print "\r\nCaught interrupt signal! Killing any child processes..."
			builtin_kill_children()
			continue

		except EOFError:
			if len(children) > 0 and warning < 1:
				warning = warning + 3 # Two commands of leeway before next warning
				print "\r\nWarning: this shell still has child processes active. Pressing ^D again will kill them."
				continue
			builtin_kill_children()
			print "\r\nLogout"
			exit()
		
		except ValueError:
			print "Unable to parse command. Do you have a non-paired delimiter? Think (), [], '', or \"\""

		except OSError:
			print "Received an OS Error. Does the file or command you're looking for exist, or are you running out of memory?"
			#traceback.print_exc()
		
		except Exception:
			print "Error: I'm unsure of how to parse/execute the previous input. Common reasons for this are multiple redirects"
			print "on the same line, commands that don't syntactically make sense, or attempting to reach files that don't exist."
			print "Nothing but whitespace will also trigger this error."
			print "Additionally, I caught the following exception:"
			traceback.print_exc()
Example #9
0
    def do_history(self, args):
        """
        This method handles all tasks related to management of history of commands

        """
        self.gLogging.debug("do_history invoked")
        description = "work with commands history"
        try:
            #import argcomplete
            parser = argparse.ArgumentParser(prog="history", add_help=True, epilog=self.epilog, description=description, usage="history <command> [<args>]")
            subparsers = parser.add_subparsers()

            clear_parser = subparsers.add_parser('clear', description="clear history", usage="history clear <args>")
            clear_parser.set_defaults(which='clear')
            clear_parser.add_argument('-Y', '--yes', action='store_true', required=True, help="confirm")

            show_parser = subparsers.add_parser('show', description="show history", usage="history show") #, aliases=['s']
            show_parser.set_defaults(which='show')

            rem_parser = subparsers.add_parser('run', description="run command again", usage="history run <args>")
            rem_parser.set_defaults(which='run')
            rem_parser.add_argument('-c', '--command', type=int, required=True, help="command number")

            find_parser = subparsers.add_parser('find', description="find command", usage="history find <args>")
            find_parser.set_defaults(which='find')
            find_parser.add_argument('-c', '--command', type=str, required=True, help="command substring")

            #completer = argcomplete.CompletionFinder(parser)
            #readline.set_completer_delims("")
            #readline.set_completer(completer.rl_complete)
            #readline.parse_and_bind("tab: complete")

            choice = vars(parser.parse_args(args.split()))
            if len(args) == 0:
                parser.print_help()
            elif choice['which'] == 'clear':
                if choice['yes']:
                    readline.clear_history()
                else:
                    self.gLogging.show("skipped.. ")
            elif choice['which'] == 'show':
                for i in range(readline.get_current_history_length()):
                    print(i+1, readline.get_history_item(i + 1))
            elif choice['which'] == 'run':
                self.onecmd(readline.get_history_item(choice['command']))
            elif choice['which'] == 'find':
                for i in range(readline.get_current_history_length()):
                    if choice['command'] in readline.get_history_item(i + 1):
                        print(i+1, readline.get_history_item(i + 1))
            else:
                parser.print_help()

        except SystemExit:
            pass
        except Exception:
            self.gLogging.error("cannot parse given arguments")
Example #10
0
def history(history_id=None):
    if history_id is None:
        for i in range(readline.get_current_history_length()):
            print(str(i + 1) + ': ' + readline.get_history_item(i + 1))
        return None

    else:

        #        print( str(history_id ) + ': ' + readline.get_history_item(history_id) )
        return readline.get_history_item(history_id)
Example #11
0
def history(history_id=None):
    if history_id is None:
        for i in range(readline.get_current_history_length()):
            print( str(i+1) + ': ' + readline.get_history_item(i+1) ) 
        return None

    else:

#        print( str(history_id ) + ': ' + readline.get_history_item(history_id) ) 
        return readline.get_history_item(history_id)
Example #12
0
 def __getitem__(self, index):
     '''
     Get a single event at ``index`` or a :class:`slice` of events.
     '''
     if isinstance(index, slice):
         start = self.normalize_index(index.start or 0)
         stop = self.normalize_index((index.stop or self.__len__())-1)
         step = index.step or 1
         return [readline.get_history_item(i) for i in range(start, stop+1, step)]
     else:
         index = self.normalize_index(index)
         return readline.get_history_item(index)
Example #13
0
def save():
    """save the readline history since last call to mark()"""
    end = readline.get_current_history_length() - 1
    session = []
    item = readline.get_history_item(end)
    while item != _marker:
        session.insert(0, item+"\n")
        end -= 1
        item = readline.get_history_item(end)
        
    file(_session_file, 'w').writelines(session)
    print >> sys.stderr, "saved session to", _session_file
Example #14
0
 def history(self, argv):
     """history [<index>]
 Display the current readline history buffer."""
     if not readline:
         self._print("The readline library is not available.")
         return
     if len(argv) > 1:
         idx = int(argv[1])
         self._print(readline.get_history_item(idx))
     else:
         for i in range(readline.get_current_history_length()):
             self._print(readline.get_history_item(i))
Example #15
0
 def history(self, argv):
     """history [<index>]
 Display the current readline history buffer."""
     if not readline:
         self._print("The readline library is not available.")
         return
     if len(argv) > 1:
         idx = int(argv[1])
         self._print(readline.get_history_item(idx))
     else:
         for i in range(readline.get_current_history_length()):
             self._print(readline.get_history_item(i))
Example #16
0
def compact_history():
    if hasattr(readline, "replace_history_item"):
        unique_history = utils.unique_list()
        for index in reversed(list(range(1, readline.get_current_history_length()))):
            hist_item = readline.get_history_item(index)
            if hist_item:  # some history items are None (usually at index 0)
                unique_history.append(readline.get_history_item(index))
        unique_history.reverse()
        for index in range(len(unique_history)):
            readline.replace_history_item(index + 1, unique_history[index])
        for index in reversed(list(range(len(unique_history) + 1, readline.get_current_history_length()))):
            readline.remove_history_item(index)
def compact_history():
    if hasattr(readline, "replace_history_item"):
        unique_history = utils.unique_list()
        for index in reversed(list(range(1, readline.get_current_history_length()))):
            hist_item = readline.get_history_item(index)
            if hist_item:  # some history items are None (usually at index 0)
                unique_history.append(readline.get_history_item(index))
        unique_history.reverse()
        for index in range(len(unique_history)):
            readline.replace_history_item(index + 1, unique_history[index])
        for index in reversed(list(range(len(unique_history) + 1, readline.get_current_history_length()))):
            readline.remove_history_item(index)
Example #18
0
def history(start=0, end=None, find=None, concat=False):
    if end is None:
        end = rl.get_current_history_length()
    if start < 0:
        start += rl.get_current_history_length()
    if concat:
        print(';'.join(
            rl.get_history_item(i + 1) for i in range(start, end)
            if find is None or find in rl.get_history_item(i + 1)))
        return
    for i in range(start, end):
        if find is None or find in rl.get_history_item(i + 1):
            print(str(i + 1) + ":", rl.get_history_item(i + 1))
Example #19
0
    def history(self, arguments):
        """Display the current readline history buffer.

        Usage:
            history [<index>]
        """
        index = arguments["<index>"]
        if index:
            idx = int(index)
            self._ui.print(readline.get_history_item(idx))
        else:
            for i in range(readline.get_current_history_length()):
                self._ui.print(readline.get_history_item(i))
Example #20
0
    def wait_input(self, prompt="", completer=None):
        """

        Wait for the user to input a message and hit enter.
        Returns the message

        """
        self.inputbuffer = prompt
        self.redraw_chatline()
        self.win_chatline.cursyncup()
        last = -1
        historyPos = 0
        while last != ord('\n'):
            # commands to execute based on which key
            # tab: complete
            # arrows: iterate history
            last = self.stdscr.getch()
            if last == ord('\n'):
                readline.add_history(self.inputbuffer)
                tmp = self.inputbuffer
                self.inputbuffer = ""
                self.redraw_chatline()
                self.win_chatline.cursyncup()
                return tmp[len(prompt):]
            elif last == ord('\t'):
                if completer != None:
                    response = completer.complete(self.inputbuffer)
                    if response:
                        self.inputbuffer = response
                else:
                    pass
            elif last == curses.KEY_UP:
                historyPos += 1
                resp = readline.get_history_item(
                    readline.get_current_history_length() - historyPos)
                if resp != None:
                    self.inputbuffer = resp
            elif last == curses.KEY_DOWN:
                historyPos -= 1
                resp = readline.get_history_item(
                    readline.get_current_history_length() - historyPos)
                if resp != None:
                    self.inputbuffer = resp
            elif last == curses.KEY_BACKSPACE or last == 127:
                if len(self.inputbuffer) > len(prompt):
                    self.inputbuffer = self.inputbuffer[:-1]
            elif last == curses.KEY_RESIZE:
                self.resize()
            elif 32 <= last <= 126:
                self.inputbuffer += chr(last)
            self.redraw_chatline()
Example #21
0
    def search(self, searchItem):

        historyLength = readline.get_current_history_length()
        historyLengthDigitNr = len(str(historyLength))

        for idx in range(1, historyLength):
            historyItem = readline.get_history_item(idx)
            if historyItem.find(searchItem) != -1:
                idxLen = len(str(idx))
                print "%(space)s%(idx)s  '%(historyItem)s'" % {
                    'space': ' ' * (1 + historyLengthDigitNr - idxLen),
                    'idx': idx,
                    'historyItem': readline.get_history_item(idx)
                }
Example #22
0
 def __getitem__(self, index):
     '''
     Get a single event at ``index`` or a :class:`slice` of events.
     '''
     if isinstance(index, slice):
         start = self.normalize_index(index.start or 0)
         stop = self.normalize_index((index.stop or self.__len__()) - 1)
         step = index.step or 1
         return [
             readline.get_history_item(i)
             for i in range(start, stop + 1, step)
         ]
     else:
         index = self.normalize_index(index)
         return readline.get_history_item(index)
Example #23
0
    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [readline.get_history_item(index) for index in xrange(readline.get_current_history_length())]
            readline.clear_history()
            map(readline.add_history, self.history)

        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix,))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code,)
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e,)
Example #24
0
    def history(self):
        """ returns all the executed commands """
        if not HAVE_READLINE:
            return

        for i in range(0, readline.get_current_history_length()):
            yield readline.get_history_item(i)
Example #25
0
def rl_autoindent():
    """Auto-indent upon typing a new line according to the contents of the
    previous line.  This function will be used as Readline's
    pre-input-hook.

    """
    hist_len = readline.get_current_history_length()
    last_input = readline.get_history_item(hist_len)
    try:
        last_indent_index = last_input.rindex("    ")
    except:
        last_indent = 0
    else:
        last_indent = int(last_indent_index / 4) + 1
    if len(last_input.strip()) > 1:
        if last_input.count("(") > last_input.count(")"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count(")") > last_input.count("("):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input.count("[") > last_input.count("]"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count("]") > last_input.count("["):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input.count("{") > last_input.count("}"):
            indent = ''.join(["    " for n in range(last_indent + 2)])
        elif last_input.count("}") > last_input.count("{"):
            indent = ''.join(["    " for n in range(last_indent - 1)])
        elif last_input[-1] == ":":
            indent = ''.join(["    " for n in range(last_indent + 1)])
        else:
            indent = ''.join(["    " for n in range(last_indent)])
    readline.insert_text(indent)
Example #26
0
def remote_log_history():
    import readline
    from time import time
    import requests
    import os
    import json
    import base64
    cnt = readline.get_current_history_length()
    for i in xrange(cnt):
        cmd = readline.get_history_item(i + 1)
        data = {}
        data['ts'] = time()
        data['cmd'] = base64.b64encode(cmd.encode('ascii'))
        data['optout'] = None
        if 'STATSOPTOUT' in os.environ:
            data['optout'] = os.environ['STATSOPTOUT']
        data['src'] = {}
        data['src']['user'] = os.environ['USER']
        if 'SESSIP' in os.environ:
            data['src']['ip'] = os.environ['SESSIP']
        pid = os.getpid()
        ppid = os.getppid()
        sessid = 'SESSID'
        if 'SESSID' in os.environ:
            sessid = os.environ['SESSID']
        data['src']['session'] = '%s.%s.%s.py' % (pid, ppid, sessid)
        url = 'http://ctf.local:9999/cmd'
        # print('request: %s' % json.dumps(data))
        try:
            requests.post(url, data=json.dumps(data), timeout=2.0)
        except:  # ConnectionError, HTTPError, Timeout, TooManyRedirects
            pass
    def wrapper(*args, **kwargs):
        try:
            import readline
            handle_readline = True
        except ImportError:
            handle_readline = False

        if handle_readline:
            # backup & reset readline completer
            old_readline_completer = readline.get_completer()
            readline.set_completer((lambda x: x))
            # backup & reset readline history
            old_readline_history = []
            hist_sz = readline.get_current_history_length()
            for i in range(1, hist_sz + 1):
                line = readline.get_history_item(i)
                old_readline_history.append(line)
            readline.clear_history()

        try:
            retval = function(*args, **kwargs)
        finally:

            if handle_readline:
                # restore old readline completer
                readline.set_completer(old_readline_completer)
                # restore old readline history
                readline.clear_history()
                for line in old_readline_history:
                    readline.add_history(line)

        return retval
Example #28
0
 def __str__(self):
     try:
         _ = readline.get_history_item(readline.get_current_history_length())
         if _ not in [h[-1], None, h]: h.append(_);
     except NameError:
        pass
     return self.str % len(h);
Example #29
0
 def __str__(self):
     global h
     h = History()
     for x in range(0,readline.get_current_history_length()-1):
       #print "length %d %s" % (x,readline.get_history_item(x))
       h.append(readline.get_history_item(x))
     return self.str % readline.get_current_history_length()
Example #30
0
    def save(self, filename, pos = None, end = None):
        """write history number from pos to end into filename file"""
        length = get_current_history_length()
        if length > 1:
            if not pos:
                pos = 1
            elif pos >= length - 1:
                pos = length - 1
            elif pos < 1:
                pos = length + pos - 1
            if not end:
                end = length
            elif end >= length:
                end = length
            if end < 0:
                end = length + end
            else:
                end = end + 1

            fp = open(filename, 'w')
            write = fp.write
            if pos < end:
                map(lambda x: write('%s\n' %  x),
                    imap(get_history_item, xrange(pos, end)))
            else:
                write('%s\n' % get_history_item(pos))
            fp.close()
Example #31
0
def builtin_history(args):
	print "\033[2J\033[1;1H" # First character clears screen, second places cursor at top-left
	print "HISTORY"
	print "-------"
	for i in range(1, int(readline.get_current_history_length())):
		print "{}. {}".format(i, readline.get_history_item(i))
	print ""
Example #32
0
def remove_history_item(line_number, initial_history_length=None):
    """
    Function to remove an item from the readline history 
    since readline.remove_history_item() is not working

    Args:
        line_number (int): History line that will removed
        initial_history_length (int): The history length recorded at the start of the Pybash session,
            used for history management.  If the removed line was prior to the initial history length, 
            then this needs to be adjusted.
    Returns:
        int: If initial_history_length was provided, the adjusted initial history length is returned
            If not, then None is returned
    """

    # Get all history items except for the one at line_number
    hist_len = readline.get_current_history_length()
    new_history = [
        readline.get_history_item(i) for i in range(1, hist_len)
        if not i == line_number
    ]

    # Replace history
    readline.clear_history()
    for l in new_history:
        readline.add_history(l)

    # If initial_history_length was specified, check to see if it needs to be adjusted
    if initial_history_length:
        if line_number < initial_history_length:
            return initial_history_length - 1
        else:
            return initial_history_length
    else:
        return
Example #33
0
 def __history_try_search(cls, text):
     history_range = range(readline.get_current_history_length(), 1, -1)
     for i in history_range:
         item = readline.get_history_item(i)
         if item.startswith(text):
             return item
     return ''
Example #34
0
    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [
                readline.get_history_item(index)
                for index in xrange(readline.get_current_history_length())
            ]
            old_history = filter(lambda x: x is not None, old_history)
            readline.clear_history()
            map(readline.add_history, self.history)

        old_completer = readline.get_completer()
        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix, ))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code, )
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e, )
Example #35
0
def hist():
    """Fetches command line history. Returns dict of all lines."""
    history_dict = {}
    # create history_list
    for i in range(readline.get_current_history_length()):
        history_dict[i+1] = (readline.get_history_item(i+1))
    return history_dict
Example #36
0
 def get_history(max_entries):
     """Get the most recently used shell commands."""
     num_entries = readline.get_current_history_length()
     return [
         readline.get_history_item(index + 1)
         for index in range(max(num_entries - max_entries, 0), num_entries)
     ]
Example #37
0
def history(command):
    """print the line of history"""
    exit_code = 0
    if len(command) == 1:
        for i in range(1, readline.get_current_history_length() + 1):
            print("%3d %s" % (i, readline.get_history_item(i)))
        return exit_code
Example #38
0
    def get_history_item (self, index):
        length = readline.get_current_history_length()
        if index > length:
            print format_text("please select an index between {0} and {1}".format(0, length))
            return None

        return readline.get_history_item(index)
Example #39
0
    def run(self, argc, argv):
        option = argv[0]
        if option == "on":
            self.local_storage.set("history", True)
            self.global_storage.set("history", True)
            self.output_information("HatSploit history: on")
        elif option == "off":
            self.local_storage.set("history", False)
            self.global_storage.set("history", False)
            self.output_information("HatSploit history: off")
        elif option in ['-c', '--clear']:
            readline.clear_history()
            with open(self.history, 'w') as history:
                history.write("")
        elif option in ['-l', '--list']:
            using_history = self.local_storage.get("history")
            if using_history:
                if readline.get_current_history_length() > 0:
                    self.output_information("HatSploit history:")

                    history_file = open(self.history, 'r')
                    history = [x.strip() for x in history_file.readlines()]
                    history_file.close()
                    for line in history:
                        self.output_empty("    * " + line)

                    for index in range(1, readline.get_current_history_length()):
                        self.output_empty("    * " + readline.get_history_item(index))
                else:
                    self.output_warning("HatSploit history empty.")
            else:
                self.output_warning("No history detected.")
        else:
            self.output_usage(self.details['Usage'])
Example #40
0
 def _SaveHistory(self):
   """Save readline history then clear history."""
   self._saved_history = []
   for idx in xrange(1, readline.get_current_history_length()+1):
     self._saved_history.append(readline.get_history_item(idx))
   for idx in xrange(readline.get_current_history_length()):
     readline.remove_history_item(0)
Example #41
0
    def last_command(self):
        """ returns the last executed command """
        if not HAVE_READLINE:
            return ""

        cur_size = readline.get_current_history_length()
        return readline.get_history_item(cur_size - 1)
Example #42
0
    def print_history (self):
        
        length = readline.get_current_history_length()

        for i in xrange(1, length + 1):
            cmd = readline.get_history_item(i)
            print "{:<5}   {:}".format(i, cmd)
Example #43
0
    def print_history (self):
        
        length = readline.get_current_history_length()

        for i in range(1, length + 1):
            cmd = readline.get_history_item(i)
            print("{:<5}   {:}".format(i, cmd))
Example #44
0
    def get_history_item (self, index):
        length = readline.get_current_history_length()
        if index > length:
            print(format_text("please select an index between {0} and {1}".format(0, length)))
            return None

        return readline.get_history_item(index)
Example #45
0
File: source.py Project: CNDW/dill
def getblocks_from_history(object, lstrip=False):# gettype=False):
    """extract code blocks from a code object using stored history"""
    import readline, inspect, types
    lbuf = readline.get_current_history_length()
    code = [readline.get_history_item(i)+'\n' for i in range(1,lbuf)]
    lnum = 0
    codeblocks = []
   #objtypes = []
    while lnum < len(code):#-1:
       if code[lnum].lstrip().startswith('def '):
           block = inspect.getblock(code[lnum:])
           lnum += len(block)
           if block[0].lstrip().startswith('def %s(' % object.func_name):
               if lstrip: block[0] = block[0].lstrip()
               codeblocks.append(block)
   #           obtypes.append(types.FunctionType)
       elif 'lambda ' in code[lnum]:
           block = inspect.getblock(code[lnum:])
           lnum += len(block)
           lhs,rhs = block[0].split('lambda ',1)[-1].split(":", 1) #FIXME: bad
           try: #FIXME: unsafe
               _ = eval("lambda %s : %s" % (lhs, rhs), globals(), locals())
           except: pass
           if _.func_code.co_code == object.func_code.co_code:
               if lstrip: block[0] = block[0].lstrip()
               codeblocks.append(block)
   #           obtypes.append('<lambda>')
       else:
           lnum +=1
   #if gettype: return codeblocks, objtypes 
    return codeblocks #XXX: danger... gets methods and closures w/o containers
Example #46
0
def getline(frame):
    """
    get the current logic line from the frame
    """
    lineno = frame.f_lineno
    filename = frame.f_code.co_filename

    if filename == "<stdin>":
        try:
            his_length = readline.get_current_history_length()
            code_string = readline.get_history_item(his_length)
        except NameError:
            raise Exception("watchpoints does not support REPL on Windows")
    elif filename.startswith("<ipython-input"):
        return inspect.getsource(frame)
    else:
        with open(filename, "r", encoding="utf-8") as f:
            lines = f.readlines()
            if sys.version_info.minor <= 7:
                # For python 3.6 and 3.7, f_lineno does not return correct position
                # when it's multiline code
                while "(" not in lines[lineno - 1]:
                    lineno -= 1
            linesio = StringIO("".join(lines[lineno - 1:]))
            lst = []
            code_string = ""
            for toknum, tokval, _, _, _ in generate_tokens(linesio.readline):
                if toknum == NEWLINE:
                    code_string = " ".join(lst)
                    break
                elif toknum not in (COMMENT, NL, INDENT):
                    lst.append(tokval)

    return code_string
Example #47
0
    def save(self, filename, pos=None, end=None):
        """write history number from pos to end into filename file"""
        length = get_current_history_length()
        if length > 1:
            if not pos:
                pos = 1
            elif pos >= length - 1:
                pos = length - 1
            elif pos < 1:
                pos = length + pos - 1
            if not end:
                end = length
            elif end >= length:
                end = length
            if end < 0:
                end = length + end
            else:
                end = end + 1

            fp = open(filename, 'w')
            write = fp.write
            if pos < end:
                map(lambda x: write('%s\n' % x),
                    imap(get_history_item, xrange(pos, end)))
            else:
                write('%s\n' % get_history_item(pos))
            fp.close()
def get_history_items():
    """迭代命令"""
    return [
        readline.get_history_item(i)
        for i in range(1,
                       readline.get_current_history_length() + 1)
    ]
Example #49
0
 def __print_history(self):
     hi_len = readline.get_current_history_length()
     offset = hi_len - 10 if hi_len > 10 else 0
     for i in range(offset, hi_len):
         item = readline.get_history_item(i)
         if item:
             print(item)
    def __init__(self, async_, console, client, save_console_history):
        self.async_ = async_
        self.lines = deque(maxlen=100)

        self.generate_prompt = console.generate_prompt
        self.save_console_history = save_console_history

        self.ac = client.get_console_methods()

        self.ac.update({
            'quit': self.action_quit,
            'q': self.action_quit,
            'exit': self.action_quit,
            'help': self.action_help,
            '?': self.action_help
        })

        # fetch readline history and add relevants
        for i in range(1, readline.get_current_history_length()):
            cmd = readline.get_history_item(i)
            if cmd.strip() and cmd.split()[0] in self.ac:
                self.lines.appendleft(CmdLine(cmd))

        # new line
        self.lines.appendleft(CmdLine(''))
        self.line_index = 0
        self.last_status = ''
Example #51
0
def getblocks(object, lstrip=False):# gettype=False):
    """extract code blocks from a code object using stored history"""
    import readline, inspect #, types
    lbuf = readline.get_current_history_length()
    code = [readline.get_history_item(i)+'\n' for i in range(1,lbuf)]
    lnum = 0
    codeblocks = []
   #objtypes = []
    try:
        if PYTHON3:
            fname = object.__name__
            ocode = object.__code__
        else:
            fname = object.func_name
            ocode = object.func_code
        cname = ''
    except AttributeError:
        fname = ''
        ocode = lambda :'__this_is_a_big_dummy_object__'
        ocode.co_code = '__this_is_a_big_dummy_co_code__'
       #try: inspect.getmro(object) #XXX: ensure that it's a class
        if hasattr(object, '__name__'): cname = object.__name__ # class
        else: cname = object.__class__.__name__ # instance
    while lnum < len(code):#-1:
        if fname and code[lnum].lstrip().startswith('def '):
            # functions and methods
            block = inspect.getblock(code[lnum:])
            lnum += len(block)
            if block[0].lstrip().startswith('def %s(' % fname):
                if lstrip: block[0] = block[0].lstrip()
                codeblocks.append(block)
   #            obtypes.append(types.FunctionType)
        elif cname and code[lnum].lstrip().startswith('class '):
            # classes and instances
            block = inspect.getblock(code[lnum:])
            lnum += len(block)
            _cname = ('class %s(' % cname, 'class %s:' % cname)
            if block[0].lstrip().startswith(_cname):
                if lstrip: block[0] = block[0].lstrip()
                codeblocks.append(block)
        elif fname and 'lambda ' in code[lnum]:
            # lambdas
            block = inspect.getblock(code[lnum:])
            lnum += len(block)
            lhs,rhs = block[0].split('lambda ',1)[-1].split(":", 1) #FIXME: bad
            try: #FIXME: unsafe
                _ = eval("lambda %s : %s" % (lhs, rhs), globals(), locals())
            except: _ = lambda : "__this_is_a_big_dummy_function__"
            if PYTHON3: _ = _.__code__
            else: _ = _.func_code
            if _.co_code == ocode.co_code:
                if lstrip: block[0] = block[0].lstrip()
                codeblocks.append(block)
   #            obtypes.append('<lambda>')
        #XXX: would be nice to grab constructor for instance, but yikes.
        else:
            lnum +=1
   #if gettype: return codeblocks, objtypes 
    return codeblocks #XXX: danger... gets methods and closures w/o containers
Example #52
0
def run_command(command, cursor):

    args = command.strip().split()

    command = args.pop(0).lower()

    if command == CMD_QUIT:
        shutdown()
    elif command == CMD_SET_EXTENDED:
        global var_extended
        var_extended = bool(args[0].lower() == 'on')
    elif command == CMD_SAVE_NEXT:
        sys.stderr.write('NOT IMPLEMENTED\n')
    elif command == CMD_SET_SAVE_FORMAT:

        if len(args) and args[0].lower() in (VALID_OUTPUT_FORMATS + ['csv']):
            global var_save_format
            var_save_format = args[0].lower()
            sys.stdout.write("SAVE_FORMAT = {0}\n".format(var_save_format))

    elif command == CMD_SET_OUTPUT_FORMAT:

        if len(args) and args[0].lower() in (VALID_OUTPUT_FORMATS + ['csv']):
            global var_output_format
            var_output_format = args[0].lower()
            sys.stdout.write("OUTPUT_FORMAT = {0}\n".format(var_output_format))

    elif command == CMD_SAVE_PREV:

        path = '/tmp/osql_save'

        if len(args):
            path = ' '.join(args)

        last = readline.get_current_history_length() - 1
        sql = readline.get_history_item(last)

        print sql

        save_query_results(cursor, sql, path)

    elif command == CMD_LIST_TABLES:
        cursor.execute("SELECT TABLE_NAME, OWNER FROM ALL_TABLES")
        rows = cursor.fetchall()
        print tabulate(rows, ['Name', 'Owner'], tablefmt='psql')
    elif command == CMD_LIST_VIEWS:
        SQL = "SELECT VIEW_NAME, OWNER FROM ALL_VIEWS"
        if len(args):
            SQL += " WHERE VIEW_NAME LIKE '%{0}%'".format(args[0])
        cursor.execute(SQL)
        rows = cursor.fetchall()
        if len(rows) > 1:
            print tabulate(rows, ['Name', 'Owner'], tablefmt='psql')
        else:
            print tabulate(describe(cursor, args[0]),
                           ['name', 'type', 'display_size', 'internal_size',
                            'precision', 'scale', 'null_ok'], tablefmt='psql')
    else:
        sys.stderr.write("Unknown command.\n")
Example #53
0
def get_history_items():
    """
    Get all history item
    """
    return [
        readline.get_history_item(i)
        for i in xrange(1, readline.get_current_history_length() + 1)
    ]
Example #54
0
File: cli.py Project: da4089/monjon
    def history(self):
        """CLI command to print history of previously-executed commands."""

        n = readline.get_current_history_length()
        for i in range(n):
            print(readline.get_history_item(i))

        return
Example #55
0
def h(recent=25):
    """show command history
    recent: number of recent command lines to show.
    """
    length = readline.get_current_history_length()
    start = 0 if length <= recent else (length - recent)
    for x in xrange(start, readline.get_current_history_length()):
        print(readline.get_history_item(x + 1))
Example #56
0
    def write_to_log(self):
        if not os.path.isfile(log_file_name):
             with open(log_file_name, 'w') as fp:
                  pass

        with open(log_file_name, 'a') as fp:
            if readline.get_current_history_length():
                fp.write(str(datetime.now()) + '\t' + readline.get_history_item(readline.get_current_history_length()) + '\n')