Python源码示例:colorama.Style.NORMAL

示例1
def color(s, c, style="bright"):
    color_map = {
        "black": Fore.BLACK,
        "red": Fore.RED,
        "green": Fore.GREEN,
        "yellow": Fore.YELLOW,
        "blue": Fore.BLUE,
        "magenta": Fore.MAGENTA,
        "cyan": Fore.CYAN,
        "white": Fore.WHITE,
    }
    style_map = {
        "dim": Style.DIM,
        "normal": Style.NORMAL,
        "bright": Style.BRIGHT,
    }

    return color_map[c] + style_map[style] + s + Style.RESET_ALL 
示例2
def parse_port_scan(stream, tag, target, pattern):
    address = target.address
    ports = []

    while True:
        line = await stream.readline()
        if line:
            line = str(line.rstrip(), 'utf8', 'ignore')
            debug(Fore.BLUE + '[' + Style.BRIGHT + address + ' ' + tag + Style.NORMAL + '] ' + Fore.RESET + '{line}', color=Fore.BLUE)

            parse_match = re.search(pattern, line)
            if parse_match:
                ports.append(parse_match.group('port'))


            for p in global_patterns:
                matches = re.findall(p['pattern'], line)
                if 'description' in p:
                    for match in matches:
                        if verbose >= 1:
                            info('Task {bgreen}{tag}{rst} on {byellow}{address}{rst} - {bmagenta}' + p['description'].replace('{match}', '{bblue}{match}{crst}{bmagenta}') + '{rst}')
                        async with target.lock:
                            with open(os.path.join(target.scandir, '_patterns.log'), 'a') as file:
                                file.writelines(e('{tag} - ' + p['description'] + '\n\n'))
                else:
                    for match in matches:
                        if verbose >= 1:
                            info('Task {bgreen}{tag}{rst} on {byellow}{address}{rst} - {bmagenta}Matched Pattern: {bblue}{match}{rst}')
                        async with target.lock:
                            with open(os.path.join(target.scandir, '_patterns.log'), 'a') as file:
                                file.writelines(e('{tag} - Matched Pattern: {match}\n\n'))
        else:
            break

    return ports 
示例3
def parse_service_detection(stream, tag, target, pattern):
    address = target.address
    services = []

    while True:
        line = await stream.readline()
        if line:
            line = str(line.rstrip(), 'utf8', 'ignore')
            debug(Fore.BLUE + '[' + Style.BRIGHT + address + ' ' + tag + Style.NORMAL + '] ' + Fore.RESET + '{line}', color=Fore.BLUE)

            parse_match = re.search(pattern, line)
            if parse_match:
                services.append((parse_match.group('protocol').lower(), int(parse_match.group('port')), parse_match.group('service')))

            for p in global_patterns:
                matches = re.findall(p['pattern'], line)
                if 'description' in p:
                    for match in matches:
                        if verbose >= 1:
                            info('Task {bgreen}{tag}{rst} on {byellow}{address}{rst} - {bmagenta}' + p['description'].replace('{match}', '{bblue}{match}{crst}{bmagenta}') + '{rst}')
                        async with target.lock:
                            with open(os.path.join(target.scandir, '_patterns.log'), 'a') as file:
                                file.writelines(e('{tag} - ' + p['description'] + '\n\n'))
                else:
                    for match in matches:
                        if verbose >= 1:
                            info('Task {bgreen}{tag}{rst} on {byellow}{address}{rst} - {bmagenta}Matched Pattern: {bblue}{match}{rst}')
                        async with target.lock:
                            with open(os.path.join(target.scandir, '_patterns.log'), 'a') as file:
                                file.writelines(e('{tag} - Matched Pattern: {match}\n\n'))
        else:
            break

    return services 
示例4
def print_out(data, end='\n'):
    datetimestr = str(datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S'))
    print(Style.NORMAL + "[" + datetimestr + "] " + data + Style.RESET_ALL,' ', end=end) 
示例5
def show_row(row):
    row = color_row(row)
    print(" ".join(["%s%s%s:%s" % (Style.NORMAL, x.capitalize(), Style.BRIGHT, y) for (x, y) in row.items()])) 
示例6
def parseLine(line):
    severity = getSeverity(line)

    # Add color based on severity
    if 'severity' not in locals():
        severity = 3

    if severity == 0:
        color = Style.DIM + Fore.WHITE
    elif severity == 1:
        color = Style.NORMAL + Fore.BLUE
    elif severity == 2:
        color = Style.NORMAL + Fore.CYAN
    elif severity == 3:
        color = Style.NORMAL + Fore.WHITE
    elif severity == 4:
        color = Style.NORMAL + Fore.RED
    elif severity == 5:
        color = Style.NORMAL + Fore.BLACK + Back.RED
    else:
        color = Style.NORMAL + Fore.BLACK + Back.YELLOW

    # Replace html tab entity with actual tabs
    line = clearTags(line)
    line = line.replace('	', "\t")
    return color + line + Style.RESET_ALL 
示例7
def __parse_prompt(self):
        raw_prompt_default_template = Style.BRIGHT + Fore.BLUE + "{host}" + Fore.RESET + " > " + Style.NORMAL
        raw_prompt_template = os.getenv("ISAF_RAW_PROMPT", raw_prompt_default_template).replace('\\033', '\033')
        self.raw_prompt_template = raw_prompt_template if '{host}' in raw_prompt_template else raw_prompt_default_template
        module_prompt_default_template = Style.BRIGHT + Fore.BLUE + "{host}" + Fore.RESET + " (" + Fore.LIGHTBLUE_EX \
                                         + "{module}" + Fore.RESET + Style.NORMAL + ") > "
        module_prompt_template = os.getenv("ISAF_MODULE_PROMPT", module_prompt_default_template).replace('\\033',
                                                                                                         '\033')
        self.module_prompt_template = module_prompt_template if all(
            map(lambda x: x in module_prompt_template, ['{host}', "{module}"])) else module_prompt_default_template 
示例8
def _show_options(self, *args, **kwargs):
        target_opts = ['target', 'port']
        module_opts = [opt for opt in self.current_module.options if opt not in target_opts]
        headers = ("Name", "Value", "Description")

        Utils.print_info(Style.BRIGHT + "\nTarget:" + Style.NORMAL)
        Utils.printTable(headers, *self.get_opts(*target_opts))

        if module_opts:
            Utils.print_info(Style.BRIGHT + "\nModule:" + Style.NORMAL)
            Utils.printTable(headers, *self.get_opts(*module_opts))

        Utils.print_info() 
示例9
def _show_devices(self, *args, **kwargs):  # TODO: cover with tests
        try:
            devices = self.current_module._Exploit__info__['devices']

            Utils.print_info(Style.BRIGHT + "\nDevices:" + Style.NORMAL)
            i = 0
            for device in devices:
                if isinstance(device, dict):
                    Utils.print_info("   {} - {}".format(i, device['name']))
                else:
                    Utils.print_info("   {} - {}".format(i, device))
                i += 1
            Utils.print_info()
        except KeyError:
            Utils.print_info("\nTarget devices not defined.") 
示例10
def printcolored(color, text):
	# available color: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET
	# available style: DIM, NORMAL, BRIGHT, RESET_ALL
	# available back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET
	if colorisok:
		COLOR = getattr(Fore, "%s"%color.upper())
		print(COLOR + Style.NORMAL + "%s"%text)
	else:
		print text 
示例11
def colored(color, text):
	# available color: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET
	# available style: DIM, NORMAL, BRIGHT, RESET_ALL
	# available back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET
	if colorisok:
		COLOR = getattr(Fore, "%s"%color.upper())
		return COLOR + Style.NORMAL + "%s"%text
	else:
		return text 
示例12
def _highlight_keywords(self, text, keywords, fore_color=Fore.GREEN):
        if keywords and self.enable_color:
            for keyword in keywords:
                regex = re.compile(keyword, re.I | re.U | re.M)
                color = fore_color + Back.RED + Style.BRIGHT
                text = regex.sub(
                    color + keyword + Back.RESET + Style.NORMAL, text)
        return text 
示例13
def log(message, color=Fore.BLUE):
    print(f'{color}{Style.DIM}[*] {Style.NORMAL}{Fore.LIGHTBLUE_EX}{message}') 
示例14
def main():
    init()

    log(f'Starting {Fore.MAGENTA}{Style.DIM}PyNubank{Style.NORMAL}{Fore.LIGHTBLUE_EX} context creation.')

    device_id = generate_random_id()

    log(f'Generated random id: {device_id}')

    cpf = input(f'[>] Enter your CPF(Numbers only): ')
    password = getpass('[>] Enter your password (Used on the app/website): ')

    generator = CertificateGenerator(cpf, password, device_id)

    log('Requesting e-mail code')
    try:
        email = generator.request_code()
    except NuException:
        log(f'{Fore.RED}Failed to request code. Check your credentials!', Fore.RED)
        return

    log(f'Email sent to {Fore.LIGHTBLACK_EX}{email}{Fore.LIGHTBLUE_EX}')
    code = input('[>] Type the code received by email: ')

    cert1, cert2 = generator.exchange_certs(code)

    save_cert(cert1, 'cert.p12')

    print(f'{Fore.GREEN}Certificates generated successfully. (cert.pem)')
    print(f'{Fore.YELLOW}Warning, keep these certificates safe (Do not share or version in git)') 
示例15
def output_error(line):
    print Fore.RED + Style.BRIGHT + "[-] !!! " + Style.NORMAL, line, Style.BRIGHT + "!!!" 
示例16
def print_path_blue(text, path):
	print(Fore.BLUE + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) 
示例17
def print_path_red(text, path):
	print(Fore.RED + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) 
示例18
def print_path_yellow(text, path):
	print(Fore.YELLOW + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) 
示例19
def print_path_green(text, path):
	print(Fore.GREEN + Style.BRIGHT + text, Style.NORMAL + path + Style.RESET_ALL) 
示例20
def print_dry_run_copy_info(source, dest):
	"""Show source -> dest copy. Replaces expanded ~ with ~ if it's at the beginning of paths.
	source and dest are trimmed in the middle if needed. Removed characters will be replaced by ...
	:param source: Can be of type str or Path
	:param dest: Can be of type str or Path
	"""
	def shorten_home(path):
		expanded_home = os.path.expanduser("~")
		path = str(path)
		if path.startswith(expanded_home):
			return path.replace(expanded_home, "~")
		return path

	def truncate_middle(path: str, acceptable_len: int):
		"""Middle truncate a string
		https://www.xormedia.com/string-truncate-middle-with-ellipsis/
		"""
		if len(path) <= acceptable_len:
			return path
		# half of the size, minus the 3 .'s
		n_2 = int(acceptable_len / 2 - 3)
		# whatever's left
		n_1 = int(acceptable_len - n_2 - 3)
		return f"{path[:n_1]}...{path[-n_2:]}"

	trimmed_source = shorten_home(source)
	trimmed_dest = shorten_home(dest)
	longest_allowed_path_len = 87
	if len(trimmed_source) + len(trimmed_dest) > longest_allowed_path_len:
		trimmed_source = truncate_middle(trimmed_source, longest_allowed_path_len)
		trimmed_dest = truncate_middle(trimmed_dest, longest_allowed_path_len)
	print(Fore.YELLOW + Style.BRIGHT + trimmed_source + Style.NORMAL, "->", Style.BRIGHT + trimmed_dest + Style.RESET_ALL) 
示例21
def print_pkg_mgr_reinstall(mgr):
	print("{}Reinstalling {}{}{}{}{}...{}".format(Fore.BLUE, Style.BRIGHT, Fore.YELLOW,
												  mgr, Fore.BLUE, Style.NORMAL, Style.RESET_ALL))


# TODO: BUG: Why does moving this to prompts.py cause circular imports? 
示例22
def output_error(line):
    print Fore.RED + Style.BRIGHT + "[-] !!! " + Style.NORMAL, line, Style.BRIGHT + "!!!" 
示例23
def __download_album(self, album):
        """
        下载单个相册
        :param album: 相册数据
        :return: None
        """
        # 相册所有图片的id
        all_photo_ids = WeiboApi.fetch_photo_ids(self.uid, album['album_id'], album['type'])
        self.logger.info(Fore.BLUE + '检测到 %d 张图片' % len(all_photo_ids))

        # 相册所有大图的数据
        all_large_pics = self.__fetch_large_pics(album, all_photo_ids)
        total = len(all_large_pics)

        # 下载所有大图
        with concurrent.futures.ThreadPoolExecutor() as executor:
            album_path = self.__make_album_path(album)

            future_to_large = {
                executor.submit(self.__download_pic, large, album_path): large
                for large in all_large_pics
            }

            for i, future in enumerate(concurrent.futures.as_completed(future_to_large)):
                large = future_to_large[future]
                count_msg = '%d/%d ' % (i + 1, total)
                try:
                    result, path = future.result()
                except Exception as exc:
                    err = '%s 抛出了异常: %s' % (WeiboApi.make_large_url(large), exc)
                    self.logger.error(''.join([Fore.RED, count_msg, err]))
                else:
                    style = result and Style.NORMAL or Style.DIM
                    self.logger.info(''.join([Fore.GREEN, style, count_msg, path]))
            else:
                self.logger.info(Fore.BLUE + '《%s》 已完成' % album['caption']) 
示例24
def main():
    colorama.init()
    pos = lambda y, x: Cursor.POS(x, y)
    # draw a white border.
    print(Back.WHITE, end='')
    print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
    for y in range(MINY, 1+MAXY):
        print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
    print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='')
    # draw some blinky lights for a while.
    for i in range(PASSES):
        print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='')
    # put cursor to top, left, and set color to white-on-black with normal brightness.
    print('%s%s%s%s' % (pos(MINY, MINX), Fore.WHITE, Back.BLACK, Style.NORMAL), end='') 
示例25
def print_out(data):
    datetimestr = str(datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S'))
    print(Style.NORMAL + "[" + datetimestr + "] " + data + Style.RESET_ALL) 
示例26
def color(out_string, color='grn'):
    """ Highlight string for terminal color coding.

    Purpose: We use this utility function to insert a ANSI/win32 color code
           | and Bright style marker before a string, and reset the color and
           | style after the string. We then return the string with these
           | codes inserted.

    @param out_string: the string to be colored
    @type out_string: str
    @param color: a string signifying which color to use. Defaults to 'grn'.
                | Accepts the following colors:
                |     ['blk', 'blu', 'cyn', 'grn', 'mag', 'red', 'wht', 'yel']
    @type color: str

    @returns: the modified string, including the ANSI/win32 color codes.
    @rtype: str
    """
    c = {
        'blk': Fore.BLACK,
        'blu': Fore.BLUE,
        'cyn': Fore.CYAN,
        'grn': Fore.GREEN,
        'mag': Fore.MAGENTA,
        'red': Fore.RED,
        'wht': Fore.WHITE,
        'yel': Fore.YELLOW,
    }
    try:
        init()
        return (c[color] + Style.BRIGHT + out_string + Fore.RESET + Style.NORMAL)
    except AttributeError:
        return out_string 
示例27
def print_header():
    """
    Shows project logo in ASCII format,
    project description and repository
    Checks dependencies for colored output
    """
    init()
    project_desc = Style.BRIGHT + Fore.WHITE + """
                 +ho:`
           `:ohh. /dddy/.
        ./ydddddd/ -hddddho:          | grapheneX |
    `:ohdddddddddds``sddddds- :.      """+Style.NORMAL+"~ Automated System Hardening Framework"+Style.BRIGHT+"""
    +ddddddddddddddh. /dds- /hdd      """+Style.NORMAL+"+ Created for Linux & Windows."+Style.BRIGHT+"""
    +dddddddddddddddd/ .. /hdddd      """+Style.NORMAL+"> https://github.com/grapheneX"+Style.BRIGHT+"""
    +ddddddddddddddddo``/hdddddd      """+Style.NORMAL+"- Copyright (C) 2019-2020"+Style.BRIGHT+"""
    +ddddddddddddddo.`+ddddddddd
    `-/+oyhddddd+``+dddddddddddd
    :o+/-.` `-` .syddddddddddddd
    +dddddddyso+:-. `.-/+oyhdddd
     -+yddddddddddddhyso/:-` `-`
        `/sddddddddddddddy+-
            -+hddddddds:`
               `/sy+-
    """+Style.NORMAL
    print(project_desc)
    logger.info("grapheneX started.")
    check_privileges() 
示例28
def run_command(command, check_output=False):
    if DEBUG:
        print(Fore.WHITE + Back.YELLOW +
              "Running `{}`".format(command) + Style.NORMAL + Back.CYAN)
    if check_output:
        return subprocess.check_output(command, shell=True)
    return subprocess.call(command, shell=True) 
示例29
def make_completed_process_report(
        result: subprocess.CompletedProcess, actual_call: t.Optional[str] = None,
        short: bool = False) -> str:
    """Create a human-readable summary of executed process."""
    out = io.StringIO()
    args_str = result.args if isinstance(result.args, str) else ' '.join(result.args)
    if actual_call is None:
        out.write('execution of "{}"'.format(args_str))
    else:
        out.write('call to {} (simulating: "{}")'.format(actual_call, args_str))
    out.write(' {}{}{}'.format(Style.BRIGHT, 'succeeded' if result.returncode == 0 else 'failed',
                               Style.NORMAL))
    if result.returncode != 0:
        out.write(' (returncode={}{}{})'.format(Fore.LIGHTRED_EX, result.returncode,
                                                Style.RESET_ALL))
    if short:
        return out.getvalue()
    out.write('\n')
    if result.stdout:
        out.write('{}stdout{}:\n'.format(Fore.CYAN, Fore.RESET))
        out.write(result.stdout.rstrip())
        out.write('\n')
    else:
        out.write('{}no stdout{}, '.format(Fore.CYAN, Fore.RESET))
    if result.stderr:
        out.write('{}stderr{}:\n'.format(Fore.CYAN, Fore.RESET))
        out.write(result.stderr.rstrip())
    else:
        out.write('{}no stderr{}, '.format(Fore.CYAN, Fore.RESET))
    # out.write('\n{}'.format(result))
    return out.getvalue() 
示例30
def cprint(*args, color=Fore.RESET, char='*', sep=' ', end='\n', frame_index=1, file=sys.stdout, **kvargs):
    frame = sys._getframe(frame_index)

    vals = {
        'bgreen':  Fore.GREEN  + Style.BRIGHT,
        'bred':    Fore.RED    + Style.BRIGHT,
        'bblue':   Fore.BLUE   + Style.BRIGHT,
        'byellow': Fore.YELLOW + Style.BRIGHT,
        'bmagenta': Fore.MAGENTA + Style.BRIGHT,

        'green':  Fore.GREEN,
        'red':    Fore.RED,
        'blue':   Fore.BLUE,
        'yellow': Fore.YELLOW,
        'magenta': Fore.MAGENTA,

        'bright': Style.BRIGHT,
        'srst':   Style.NORMAL,
        'crst':   Fore.RESET,
        'rst':    Style.NORMAL + Fore.RESET
    }

    vals.update(frame.f_globals)
    vals.update(frame.f_locals)
    vals.update(kvargs)

    unfmt = ''
    if char is not None:
        unfmt += color + '[' + Style.BRIGHT + char + Style.NORMAL + ']' + Fore.RESET + sep
    unfmt += sep.join(args)

    fmted = unfmt

    for attempt in range(10):
        try:
            fmted = string.Formatter().vformat(unfmt, args, vals)
            break
        except KeyError as err:
            key = err.args[0]
            unfmt = unfmt.replace('{' + key + '}', '{{' + key + '}}')

    print(fmted, sep=sep, end=end, file=file)