def more(text): r"""more(text) Shows text like the command line tool ``more``. It not in term_mode, just prints the data to the screen. Arguments: text(str): The text to show. Returns: :const:`None` Tests: >>> more("text") text >>> p = testpwnproc("more('text\\n' * (term.height + 2))") >>> p.send(b"x") >>> b"text" in p.recvall() True """ if term.term_mode: lines = text.split('\n') h = term.output(term.text.reverse('(more)'), float=True, frozen=False) step = term.height - 1 for i in range(0, len(lines), step): for l in lines[i:i + step]: print(l) if i + step < len(lines): term.key.get() h.delete() else: print(text)
def more(text): """more(text) Shows text like the command line tool ``more``. It not in term_mode, just prints the data to the screen. Arguments: text(str): The text to show. Returns: :const:`None` """ if term.term_mode: lines = text.split('\n') h = term.output(term.text.reverse('(more)'), float=True, frozen=False) step = term.height - 1 for i in range(0, len(lines), step): for l in lines[i:i + step]: print(l) if i + step < len(lines): term.key.get() h.delete() else: print(text)
def updater(): colors = [ text.blue , text.bold_blue , text.magenta, text.bold_magenta, text.red , text.bold_red , text.yellow , text.bold_yellow , text.green , text.bold_green , text.cyan , text.bold_cyan , ] def getcolor(n): return colors[(n / 4) % len(colors)] lines = [' ' + line + '\n' for line in _banner.strip('\n').split('\n')] hs = [term.output('', frozen = False) for _ in range(len(lines))] ndx = 0 import sys as _sys while _sys: for i, (l, h) in enumerate(zip(lines, hs)): cur = '' buf = '' col = getcolor(ndx + i) for j in range(len(l)): buf += l[j] ncol = getcolor(ndx + i + j) if col != ncol: cur += buf if buf.isspace() else col(buf) col = ncol buf = '' cur += col(buf) h.update(cur) ndx += 1 time.sleep(0.15)
def more(text): """more(text) Shows text like the command line tool ``more``. It not in term_mode, just prints the data to the screen. Arguments: text(str): The text to show. Returns: :const:`None` """ if term.term_mode: lines = text.split('\n') h = term.output(term.text.reverse('(more)'), float = True, frozen = False) step = term.height - 1 for i in range(0, len(lines), step): for l in lines[i:i + step]: print l if i + step < len(lines): term.key.get() h.delete() else: print text
def yesno(prompt, default=None): """Presents the user with prompt (typically in the form of question) which the user must answer yes or no. Arguments: prompt (str): The prompt to show default : The default option; `True` means "yes" Returns: `True` if the answer was "yes", `False` if "no" """ if not isinstance(default, (bool, types.NoneType)): raise ValueError('yesno(): default must be a boolean or None') if term.term_mode: term.output(' [{qm}] {prompt} ['.format(qm=term.text.bold_cyan('?'), prompt=prompt)) yesfocus, yes = term.text.bold('Yes'), 'yes' nofocus, no = term.text.bold('No'), 'no' hy = term.output(yesfocus if default == True else yes) term.output('/') hn = term.output(nofocus if default == False else no) term.output(']\n') cur = default while True: k = term.key.get() if k in ('y', 'Y', '<left>') and cur != True: cur = True hy.update(yesfocus) hn.update(no) elif k in ('n', 'N', '<right>') and cur != False: cur = False hy.update(yes) hn.update(nofocus) elif k == '<enter>': if cur is not None: return cur else: prompt = ' [{qm}] {prompt} [{yes}/{no}] '.format( qm=term.text.bold_cyan('?'), prompt=prompt, yes='Yes' if default == True else 'yes', no='No' if default == False else 'no') while True: opt = raw_input(prompt).lower() if opt == '' and default != None: return default elif opt in ('y', 'yes'): return True elif opt in ('n', 'no'): return False print 'Please answer yes or no'
def yesno(prompt, default = None): """Presents the user with prompt (typically in the form of question) which the user must answer yes or no. Arguments: prompt (str): The prompt to show default: The default option; `True` means "yes" Returns: `True` if the answer was "yes", `False` if "no" """ if not isinstance(default, (bool, types.NoneType)): raise ValueError('yesno(): default must be a boolean or None') if term.term_mode: term.output(' [?] %s [' % prompt) yesfocus, yes = term.text.bold('Yes'), 'yes' nofocus, no = term.text.bold('No'), 'no' hy = term.output(yesfocus if default == True else yes) term.output('/') hn = term.output(nofocus if default == False else no) term.output(']\n') cur = default while True: k = term.key.get() if k in ('y', 'Y', '<left>') and cur != True: cur = True hy.update(yesfocus) hn.update(no) elif k in ('n', 'N', '<right>') and cur != False: cur = False hy.update(yes) hn.update(nofocus) elif k == '<enter>': if cur is not None: return cur else: prompt = ' [?] %s [%s/%s] ' % (prompt, 'Yes' if default == True else 'yes', 'No' if default == False else 'no', ) while True: opt = raw_input(prompt).lower() if opt == '' and default != None: return default elif opt in ('y','yes'): return True elif opt in ('n', 'no'): return False print 'Please answer yes or no'
def updater(): colors = [ text.blue, text.bold_blue, text.magenta, text.bold_magenta, text.red, text.bold_red, text.yellow, text.bold_yellow, text.green, text.bold_green, text.cyan, text.bold_cyan, ] def getcolor(n): return colors[(n / 4) % len(colors)] lines = [ ' ' + line + '\n' for line in _banner.strip('\n').split('\n') ] hs = [term.output('', frozen=False) for _ in range(len(lines))] ndx = 0 import sys as _sys while _sys: for i, (l, h) in enumerate(zip(lines, hs)): cur = '' buf = '' col = getcolor(ndx + i) for j in range(len(l)): buf += l[j] ncol = getcolor(ndx + i + j) if col != ncol: cur += buf if buf.isspace() else col(buf) col = ncol buf = '' cur += col(buf) h.update(cur) ndx += 1 time.sleep(0.15)
def options(prompt, opts, default=None): """Presents the user with a prompt (typically in the form of a question) and a number of options. Arguments: prompt (str): The prompt to show opts (list): The options to show to the user default: The default option to choose Returns: The users choice in the form of an integer. """ if not isinstance(default, six.integer_types + (types.NoneType, )): raise ValueError('options(): default must be a number or None') if term.term_mode: numfmt = '%' + str(len(str(len(opts)))) + 'd) ' print(' [?] ' + prompt) hs = [] space = ' ' arrow = term.text.bold_green(' => ') cur = default for i, opt in enumerate(opts): h = term.output(arrow if i == cur else space, frozen=False) num = numfmt % (i + 1) term.output(num) term.output(opt + '\n', indent=len(num) + len(space)) hs.append(h) ds = '' prev = 0 while True: prev = cur was_digit = False k = term.key.get() if k == '<up>': if cur is None: cur = 0 else: cur = max(0, cur - 1) elif k == '<down>': if cur is None: cur = 0 else: cur = min(len(opts) - 1, cur + 1) elif k == 'C-<up>': cur = 0 elif k == 'C-<down>': cur = len(opts) - 1 elif k in ('<enter>', '<right>'): if cur is not None: return cur elif k in tuple('1234567890'): was_digit = True d = str(k) n = int(ds + d) if n > 0 and n <= len(opts): ds += d elif d != '0': ds = d n = int(ds) cur = n - 1 if prev != cur: if prev is not None: hs[prev].update(space) if was_digit: hs[cur].update(term.text.bold_green('%5s> ' % ds)) else: hs[cur].update(arrow) else: linefmt = ' %' + str(len(str(len(opts)))) + 'd) %s' while True: print(' [?] ' + prompt) for i, opt in enumerate(opts): print(linefmt % (i + 1, opt)) s = ' Choice ' if default: s += '[%s] ' % str(default) try: x = int(raw_input(s) or default) except (ValueError, TypeError): continue if x >= 1 and x <= len(opts): return x
def emit(self, record): """ Emit a log record or create/update an animated progress logger depending on whether :data:`term.term_mode` is enabled. """ # We have set the root 'pwnlib' logger to have a logLevel of 1, # when logging has been enabled via install_default_handler. # # If the level is 1, we should only process the record if # context.log_level is less than the record's log level. # # If the level is not 1, somebody else expressly set the log # level somewhere on the tree, and we should use that value. level = logging.getLogger(record.name).getEffectiveLevel() if level == 1: level = context.log_level if level > record.levelno: return progress = getattr(record, 'pwnlib_progress', None) # if the record originates from a `Progress` object and term handling # is enabled we can have animated spinners! so check that if progress is None or not term.term_mode: super(Handler, self).emit(record) return # yay, spinners! # since we want to be able to update the spinner we overwrite the # message type so that the formatter doesn't output a prefix symbol msgtype = record.pwnlib_msgtype record.pwnlib_msgtype = 'animated' msg = "%s\n" % self.format(record) # we enrich the `Progress` object to keep track of the spinner if not hasattr(progress, '_spinner_handle'): spinner_handle = term.output('') msg_handle = term.output(msg) stop = threading.Event() def spin(): '''Wheeeee!''' state = 0 states = random.choice(spinners.spinners) while True: prefix = '[%s] ' % _spinner_style(states[state]) spinner_handle.update(prefix) state = (state + 1) % len(states) if stop.wait(0.1): break t = Thread(target=spin) t.daemon = True t.start() progress._spinner_handle = spinner_handle progress._msg_handle = msg_handle progress._stop_event = stop progress._spinner_thread = t else: progress._msg_handle.update(msg) # if the message type was not a status message update, then we should # stop the spinner if msgtype != 'status': progress._stop_event.set() progress._spinner_thread.join() style, symb = _msgtype_prefixes[msgtype] prefix = '[%s] ' % style(symb) progress._spinner_handle.update(prefix)
def init(text): lines = get_lines(text) #text.split('\n') step = term.height - 1 c = term.output(getprintable(lines, 0, step), float=True, frozen=False) f = term.output(term.text.reverse('(more)'), float=True, frozen=False) return (lines, step, c, f)
def yesno(prompt, default=None): r"""Presents the user with prompt (typically in the form of question) which the user must answer yes or no. Arguments: prompt (str): The prompt to show default: The default option; `True` means "yes" Returns: `True` if the answer was "yes", `False` if "no" Examples: >>> yesno("A number:", 20) Traceback (most recent call last): ... ValueError: yesno(): default must be a boolean or None >>> saved_stdin = sys.stdin >>> try: ... sys.stdin = io.TextIOWrapper(io.BytesIO(b"x\nyes\nno\n\n")) ... yesno("is it good 1") ... yesno("is it good 2", True) ... yesno("is it good 3", False) ... finally: ... sys.stdin = saved_stdin [?] is it good 1 [yes/no] Please answer yes or no [?] is it good 1 [yes/no] True [?] is it good 2 [Yes/no] False [?] is it good 3 [yes/No] False Tests: >>> p = testpwnproc("print(yesno('is it ok??'))") >>> b"is it ok" in p.recvuntil("??") True >>> p.sendline(b"x\nny") >>> b"True" in p.recvall() True """ if default is not None and not isinstance(default, bool): raise ValueError('yesno(): default must be a boolean or None') if term.term_mode: term.output(' [?] %s [' % prompt) yesfocus, yes = term.text.bold('Yes'), 'yes' nofocus, no = term.text.bold('No'), 'no' hy = term.output(yesfocus if default is True else yes) term.output('/') hn = term.output(nofocus if default is False else no) term.output(']\n') cur = default while True: k = term.key.get() if k in ('y', 'Y', '<left>') and cur is not True: cur = True hy.update(yesfocus) hn.update(no) elif k in ('n', 'N', '<right>') and cur is not False: cur = False hy.update(yes) hn.update(nofocus) elif k == '<enter>': if cur is not None: return cur else: prompt = ' [?] %s [%s/%s] ' % ( prompt, 'Yes' if default is True else 'yes', 'No' if default is False else 'no', ) while True: opt = raw_input(prompt).strip().lower() if not opt and default is not None: return default elif opt in (b'y', b'yes'): return True elif opt in (b'n', b'no'): return False print('Please answer yes or no')
def options(prompt, opts, default=None): r"""Presents the user with a prompt (typically in the form of a question) and a number of options. Arguments: prompt (str): The prompt to show opts (list): The options to show to the user default: The default option to choose Returns: The users choice in the form of an integer. Examples: >>> options("Select a color", ("red", "green", "blue"), "green") Traceback (most recent call last): ... ValueError: options(): default must be a number or None Tests: >>> p = testpwnproc("print(options('select a color', ('red', 'green', 'blue')))") >>> p.sendline(b"\33[C\33[A\33[A\33[B\33[1;5A\33[1;5B 0310") >>> _ = p.recvall() >>> saved_stdin = sys.stdin >>> try: ... sys.stdin = io.TextIOWrapper(io.BytesIO(b"\n4\n\n3\n")) ... with context.local(log_level="INFO"): ... options("select a color A", ("red", "green", "blue"), 0) ... options("select a color B", ("red", "green", "blue")) ... finally: ... sys.stdin = saved_stdin [?] select a color A 1) red 2) green 3) blue Choice [1] 0 [?] select a color B 1) red 2) green 3) blue Choice [?] select a color B 1) red 2) green 3) blue Choice [?] select a color B 1) red 2) green 3) blue Choice 2 """ if default is not None and not isinstance(default, six.integer_types): raise ValueError('options(): default must be a number or None') if term.term_mode: numfmt = '%' + str(len(str(len(opts)))) + 'd) ' print(' [?] ' + prompt) hs = [] space = ' ' arrow = term.text.bold_green(' => ') cur = default for i, opt in enumerate(opts): h = term.output(arrow if i == cur else space, frozen=False) num = numfmt % (i + 1) term.output(num) term.output(opt + '\n', indent=len(num) + len(space)) hs.append(h) ds = '' while True: prev = cur was_digit = False k = term.key.get() if k == '<up>': if cur is None: cur = 0 else: cur = max(0, cur - 1) elif k == '<down>': if cur is None: cur = 0 else: cur = min(len(opts) - 1, cur + 1) elif k == 'C-<up>': cur = 0 elif k == 'C-<down>': cur = len(opts) - 1 elif k in ('<enter>', '<right>'): if cur is not None: return cur elif k in tuple(string.digits): was_digit = True d = str(k) n = int(ds + d) if 0 < n <= len(opts): ds += d cur = n - 1 elif d != '0': ds = d n = int(ds) cur = n - 1 if prev != cur: if prev is not None: hs[prev].update(space) if was_digit: hs[cur].update(term.text.bold_green('%5s> ' % ds)) else: hs[cur].update(arrow) else: linefmt = ' %' + str(len(str(len(opts)))) + 'd) %s' if default is not None: default += 1 while True: print(' [?] ' + prompt) for i, opt in enumerate(opts): print(linefmt % (i + 1, opt)) s = ' Choice ' if default: s += '[%s] ' % str(default) try: x = int(raw_input(s) or default) except (ValueError, TypeError): continue if x >= 1 and x <= len(opts): return x - 1
def options(prompt, opts, default = None): """Presents the user with a prompt (typically in the form of a question) and a number of options. Arguments: prompt (str): The prompt to show opts (list): The options to show to the user default: The default option to choose Returns: The users choice in the form of an integer. """ if not isinstance(default, (int, long, types.NoneType)): raise ValueError('options(): default must be a number or None') if term.term_mode: numfmt = '%' + str(len(str(len(opts)))) + 'd) ' print ' [?] ' + prompt hs = [] space = ' ' arrow = term.text.bold_green(' => ') cur = default for i, opt in enumerate(opts): h = term.output(arrow if i == cur else space, frozen = False) num = numfmt % (i + 1) term.output(num) term.output(opt + '\n', indent = len(num) + len(space)) hs.append(h) ds = '' prev = 0 while True: prev = cur was_digit = False k = term.key.get() if k == '<up>': if cur is None: cur = 0 else: cur = max(0, cur - 1) elif k == '<down>': if cur is None: cur = 0 else: cur = min(len(opts) - 1, cur + 1) elif k == 'C-<up>': cur = 0 elif k == 'C-<down>': cur = len(opts) - 1 elif k in ('<enter>', '<right>'): if cur is not None: return cur elif k in tuple('1234567890'): was_digit = True d = str(k) n = int(ds + d) if n > 0 and n <= len(opts): ds += d elif d != '0': ds = d n = int(ds) cur = n - 1 if prev != cur: if prev is not None: hs[prev].update(space) if was_digit: hs[cur].update(term.text.bold_green('%5s> ' % ds)) else: hs[cur].update(arrow) else: linefmt = ' %' + str(len(str(len(opts)))) + 'd) %s' while True: print ' [?] ' + prompt for i, opt in enumerate(opts): print linefmt % (i + 1, opt) s = ' Choice ' if default: s += '[%s] ' % str(default) try: x = int(raw_input(s) or default) except (ValueError, TypeError): continue if x >= 1 and x <= len(opts): return x
def emit(self, record): """ Emit a log record or create/update an animated progress logger depending on whether :data:`term.term_mode` is enabled. """ # We have set the root 'pwnlib' logger to have a logLevel of 1, # when logging has been enabled via install_default_handler. # # If the level is 1, we should only process the record if # context.log_level is less than the record's log level. # # If the level is not 1, somebody else expressly set the log # level somewhere on the tree, and we should use that value. level = logging.getLogger(record.name).getEffectiveLevel() if level == 1: level = context.log_level if level > record.levelno: return progress = getattr(record, 'pwnlib_progress', None) # if the record originates from a `Progress` object and term handling # is enabled we can have animated spinners! so check that if progress is None or not term.term_mode: super(Handler, self).emit(record) return # yay, spinners! # since we want to be able to update the spinner we overwrite the # message type so that the formatter doesn't output a prefix symbol msgtype = record.pwnlib_msgtype record.pwnlib_msgtype = 'animated' msg = "%s\n" % self.format(record) # we enrich the `Progress` object to keep track of the spinner if not hasattr(progress, '_spinner_handle'): spinner_handle = term.output('') msg_handle = term.output(msg) stop = threading.Event() def spin(): '''Wheeeee!''' state = 0 states = random.choice(spinners.spinners) while True: prefix = '[%s] ' % _spinner_style(states[state]) spinner_handle.update(prefix) state = (state + 1) % len(states) if stop.wait(0.1): break t = Thread(target = spin) t.daemon = True t.start() progress._spinner_handle = spinner_handle progress._msg_handle = msg_handle progress._stop_event = stop progress._spinner_thread = t else: progress._msg_handle.update(msg) # if the message type was not a status message update, then we should # stop the spinner if msgtype != 'status': progress._stop_event.set() progress._spinner_thread.join() style, symb = _msgtype_prefixes[msgtype] prefix = '[%s] ' % style(symb) progress._spinner_handle.update(prefix)