Python colorama.Fore() Examples

The following are 30 code examples of colorama.Fore(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama , or try the search function .
Example #1
Source File: bamf.py    From bamf with GNU General Public License v3.0 6 votes vote down vote up
def _map(self, ip, port):
        request = self.open('http://{}:{}/Home/h_dhcp.htm'.format(ip, port), timeout=3.0)
        html = request.get_data().splitlines()
        for line in html:
            try:
                parts = line.split('","')
                if len(parts) >= 3 and valid_ip(parts[1]):
                    if 'ist=[' not in line and 'erver=[' not in line:

                        name = parts[0].strip('["')
                        lan_ip = parts[1]
                        mac = parts[2]
                        lan_device = {"router": ip, "device": name, "ip": lan_ip, "mac": mac}

                        self._devices.append(lan_device)

                        print('  |')
                        print(colorama.Fore.CYAN + colorama.Style.BRIGHT + '[+]' + colorama.Fore.RESET + ' Device {}'.format(len(self._devices)) + colorama.Style.NORMAL)
                        print('  |   Device Name: ' + colorama.Style.DIM + name + colorama.Style.NORMAL)
                        print('  |   Internal IP: ' + colorama.Style.DIM + lan_ip + colorama.Style.NORMAL)
                        print('  |   MAC Address: ' + colorama.Style.DIM + mac + colorama.Style.NORMAL)

            except Exception as e:
                debug(str(e)) 
Example #2
Source File: urls_helpers.py    From opencv-engine with MIT License 6 votes vote down vote up
def try_url(self, fetcher, url):
        result = None
        failed = False

        try:
            result = fetcher("/%s" % url)
        except Exception:
            logging.exception('Error in %s' % url)
            failed = True

        if result is not None and result.code == 200 and not failed:
            print("{0.GREEN} SUCCESS ({1}){0.RESET}".format(Fore, url))
            return

        self.failed_items.append(url)
        print("{0.RED} FAILED ({1}) - ERR({2}) {0.RESET}".format(Fore, url, result and result.code)) 
Example #3
Source File: server.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def settings(self):
        """
        Show the server's currently configured settings

        """
        text_color = [color for color in filter(str.isupper, dir(colorama.Fore)) if color == self._text_color][0]
        text_style = [style for style in filter(str.isupper, dir(colorama.Style)) if style == self._text_style][0]
        prompt_color = [color for color in filter(str.isupper, dir(colorama.Fore)) if color == self._prompt_color][0]
        prompt_style = [style for style in filter(str.isupper, dir(colorama.Style)) if style == self._prompt_style][0]
        util.display('\n\t    OPTIONS', color='white', style='bright')
        util.display('text color/style: ', color='white', style='normal', end=' ')
        util.display('/'.join((self._text_color.title(), self._text_style.title())), color=self._text_color, style=self._text_style)
        util.display('prompt color/style: ', color='white', style='normal', end=' ')
        util.display('/'.join((self._prompt_color.title(), self._prompt_style.title())), color=self._prompt_color, style=self._prompt_style)
        util.display('debug: ', color='white', style='normal', end=' ')
        util.display('True\n' if globals()['debug'] else 'False\n', color='green' if globals()['debug'] else 'red', style='normal') 
Example #4
Source File: color_functions.py    From rainbow with GNU Lesser General Public License v3.0 5 votes vote down vote up
def color(name, x):
    return f"{getattr(colorama.Fore,name)}{x}{_RST}" 
Example #5
Source File: utils.py    From pycobertura with MIT License 5 votes vote down vote up
def colorize(text, color):
    color_code = getattr(colorama.Fore, color.upper())
    return "%s%s%s" % (color_code, text, colorama.Fore.RESET) 
Example #6
Source File: checker.py    From PyPS3tools with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #7
Source File: checker.py    From PyPS3tools with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #8
Source File: options.py    From loopy with MIT License 5 votes vote down vote up
def _fore(self):
        if self.allow_terminal_colors:
            import colorama
            return colorama.Fore
        else:
            return _ColoramaStub() 
Example #9
Source File: traceback.py    From myia with MIT License 5 votes vote down vote up
def _print_lines(
    lines, l1, c1, l2, c2, label="", mode=None, color="RED", file=sys.stderr
):
    if mode is None:
        if file.isatty():
            mode = "color"
    for ln in range(l1, l2 + 1):
        line = lines[ln - 1]
        if ln == l1:
            trimmed = line.lstrip()
            to_trim = len(line) - len(trimmed)
            start = c1 - to_trim
        else:
            trimmed = line[to_trim:]
            start = 0

        if ln == l2:
            end = c2 - to_trim
        else:
            end = len(trimmed)

        if mode == "color":
            prefix = trimmed[:start]
            hl = trimmed[start:end]
            rest = trimmed[end:]
            print(
                f"{ln}: {prefix}{getattr(Fore, color)}{Style.BRIGHT}"
                f"{hl}{Style.RESET_ALL}{rest}",
                file=file,
            )
        else:
            print(f"{ln}: {trimmed}", file=file)
            prefix = " " * (start + 2 + len(str(ln)))
            print(prefix + "^" * (end - start) + label, file=file) 
Example #10
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def display(output, color=None, style=None, end='\n', event=None, lock=None):
    """
    Display output in the console

    `Required`
    :param str output:    text to display

    `Optional`
    :param str color:     red, green, cyan, magenta, blue, white
    :param str style:     normal, bright, dim
    :param str end:       __future__.print_function keyword arg
    :param lock:          threading.Lock object
    :param event:         threading.Event object

    """
    # if isinstance(output, bytes):
    #     output = output.decode('utf-8')
    # else:
    #     output = str(output)
    # _color = ''
    # if color:
    #     _color = getattr(colorama.Fore, color.upper())
    # _style = ''
    # if style:
    #     _style = getattr(colorama.Style, style.upper())
    # exec("""print(_color + _style + output + colorama.Style.RESET_ALL, end="{}")""".format(end))
    print(output) 
Example #11
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def display(output, color=None, style=None, end='\n', event=None, lock=None):
    """
    Display output in the console

    `Required`
    :param str output:    text to display

    `Optional`
    :param str color:     red, green, cyan, magenta, blue, white
    :param str style:     normal, bright, dim
    :param str end:       __future__.print_function keyword arg
    :param lock:          threading.Lock object
    :param event:         threading.Event object

    """
    # if isinstance(output, bytes):
    #     output = output.decode('utf-8')
    # else:
    #     output = str(output)
    # _color = ''
    # if color:
    #     _color = getattr(colorama.Fore, color.upper())
    # _style = ''
    # if style:
    #     _style = getattr(colorama.Style, style.upper())
    # exec("""print(_color + _style + output + colorama.Style.RESET_ALL, end="{}")""".format(end))
    print(output) 
Example #12
Source File: server.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def _get_prompt(self, data):
        with self._lock:
            return raw_input(getattr(colorama.Fore, self._prompt_color) + getattr(colorama.Style, self._prompt_style) + data.rstrip()) 
Example #13
Source File: util.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def display(output, color=None, style=None, end='\\n', event=None, lock=None):
    """
    Display output in the console

    `Required`
    :param str output:    text to display

    `Optional`
    :param str color:     red, green, cyan, magenta, blue, white
    :param str style:     normal, bright, dim
    :param str end:       __future__.print_function keyword arg
    :param lock:          threading.Lock object
    :param event:         threading.Event object

    """
    if isinstance(output, bytes):
        output = output.decode('utf-8')
    else:
        output = str(output)
    _color = ''
    if color:
        _color = getattr(colorama.Fore, color.upper())
    _style = ''
    if style:
        _style = getattr(colorama.Style, style.upper())
    exec("""print(_color + _style + output + colorama.Style.RESET_ALL, end="{}")""".format(end)) 
Example #14
Source File: termcolors.py    From vistir with ISC License 5 votes vote down vote up
def colorize(text, fg=None, bg=None, attrs=None):
    if os.getenv("ANSI_COLORS_DISABLED") is None:
        style = "NORMAL"
        if attrs is not None and not isinstance(attrs, list):
            _attrs = []
            if isinstance(attrs, six.string_types):
                _attrs.append(attrs)
            else:
                _attrs = list(attrs)
            attrs = _attrs
        if attrs and "bold" in attrs:
            style = "BRIGHT"
            attrs.remove("bold")
        if fg is not None:
            fg = fg.upper()
            text = to_native_string("%s%s%s%s%s") % (
                to_native_string(getattr(colorama.Fore, fg)),
                to_native_string(getattr(colorama.Style, style)),
                to_native_string(text),
                to_native_string(colorama.Fore.RESET),
                to_native_string(colorama.Style.NORMAL),
            )

        if bg is not None:
            bg = bg.upper()
            text = to_native_string("%s%s%s%s") % (
                to_native_string(getattr(colorama.Back, bg)),
                to_native_string(text),
                to_native_string(colorama.Back.RESET),
                to_native_string(colorama.Style.NORMAL),
            )

        if attrs is not None:
            fmt_str = to_native_string("%s[%%dm%%s%s[9m") % (chr(27), chr(27))
            for attr in attrs:
                text = fmt_str % (ATTRIBUTES[attr], text)

        text += RESET
    else:
        text = ANSI_REMOVAL_RE.sub("", text)
    return text 
Example #15
Source File: io.py    From evillimiter with MIT License 5 votes vote down vote up
def ok(text, end='\n'):
        """
        Print a success status message
        """
        IO.print('{}OK{}   {}'.format(IO.Style.BRIGHT + IO.Fore.LIGHTGREEN_EX, IO.Style.RESET_ALL, text), end=end) 
Example #16
Source File: io.py    From evillimiter with MIT License 5 votes vote down vote up
def error(text):
        """
        Print an error status message
        """
        IO.print('{}ERR{}  {}'.format(IO.Style.BRIGHT + IO.Fore.LIGHTRED_EX, IO.Style.RESET_ALL, text)) 
Example #17
Source File: util.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def color_conditions(
    input_obj: _T,
    prefix: Optional[str] = None,
    postfix: Optional[str] = None,
    **kwargs: Callable[[_T], bool],
) -> str:
    prefix = prefix or ''
    postfix = postfix or ''
    color_str = ''
    for color, condition in kwargs.items():
        if condition(input_obj):
            color_str = getattr(Fore, color.upper())
            break
    return color_str + prefix + str(input_obj) + postfix + Style.RESET_ALL 
Example #18
Source File: crayons.py    From crayons with MIT License 5 votes vote down vote up
def color_str(self):
        style = 'BRIGHT' if self.bold else 'NORMAL'
        c = '%s%s%s%s%s' % (getattr(colorama.Fore, self.color),
                            getattr(colorama.Style, style),
                            self.s,
                            colorama.Fore.RESET,
                            colorama.Style.NORMAL)

        if self.always_color:
            return c
        elif sys.stdout.isatty() and not DISABLE_COLOR:
            return c
        else:
            return self.s 
Example #19
Source File: io.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def color(color, string):
    s = _convert_to_string(string)
    if term_is_colorable():
        colorama.init()
        color = _remap_color(color)
        color_code = getattr(colorama.Fore, color.upper())
        return color_code + s + colorama.Fore.RESET
    else:
        return s 
Example #20
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def error(msg, color='RED'):
    print ('\n' + getattr(colorama.Fore, color)  + colorama.Style.BRIGHT + '[-] ' + colorama.Fore.WHITE + 'Error - '   + colorama.Style.NORMAL + msg + '\n') 
Example #21
Source File: util.py    From knack with MIT License 5 votes vote down vote up
def __str__(self):
        import colorama
        if not self._color:
            return self._message
        return self._color + self._message + colorama.Fore.RESET 
Example #22
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def _scan(self, ip, port):
        target = 'http://{}:{}'.format(ip, port)
        debug("Requesting {}".format(target))
        try:

            self._semaphore.acquire()

            conn = self.open(target, timeout=2.0)
            html = conn.get_data()

            if not html or not self.viewing_html():
                return

            elif conn.code == 200:
                for signature in self.__signatures:
                    if signature in html:

                        model = str(self.title())

                        self._backdoors.append({"ip": ip, "port": port, "model": model, "vulnerability": self.__vulnerability, "signature": signature})

                        print("  | ")
                        print("  |      " +  colorama.Fore.GREEN + colorama.Style.BRIGHT + "[+] " + colorama.Fore.RESET + " Backdoor {}".format(str(len(self._backdoors))) + colorama.Style.NORMAL)
                        print("  |      IP: " + colorama.Style.DIM + ip + colorama.Style.NORMAL)
                        print("  |      Port: " + colorama.Style.DIM + "{}/tcp".format(port) + colorama.Style.NORMAL)
                        print("  |      Model: " + colorama.Style.DIM + model + colorama.Style.NORMAL)
                        print("  |      Vulnerability: " + colorama.Style.DIM + self.__vulnerability + colorama.Style.NORMAL)
                        print("  |      Signature: " + colorama.Style.DIM + signature + colorama.Style.NORMAL)
            else:
                return

            self._semaphore.release()

        except KeyboardInterrupt:
            return
        except Exception as e:
            debug(str(e)) 
Example #23
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def pharm(self, dns):
        """
        Change the primary DNS server of vulnerable routers

        `Required`
        :param str dns:     IP address of a user-controlled DNS server

        """
        try:
            if not len(self._backdoors):
                error("no backdoored routers to pharm (use 'scan' to detect vulnerable targets)")
            elif not valid_ip(dns):
                error("invalid IP address entered for DNS server")
            else:
                for i, router in enumerate(self._backdoors):

                    self._pharm(router['ip'], router['port'], dns)

                    devices = self._database.execute("SELECT (SELECT count() from tbl_devices WHERE router=:router) as count", {"router": ip}).fetchall()[0][0]

                    print(colorama.Fore.MAGENTA + colorama.Style.NORMAL + '[+]' + colorama.Fore.RESET + ' Router {}:{} - DNS Server Modified'.format(ip, port))
                    print('  |   DNS Server:   ' + colorama.Style.DIM + '{}:53'.format(dns) + colorama.Style.NORMAL)
                    print('  |   Connected Devices: ' + colorama.Style.DIM + '{}\n'.format(size) + colorama.Style.NORMAL)

        except KeyboardInterrupt:
            return
        except Exception as e:
            debug(str(e)) 
Example #24
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def scan(self, *args):
        """
        Scan target hosts for signatures of a backdoor

        `Optional`
        :param str ip:      IP address of target router
        :param int port:    Port number of router administration panel

        """
        try:
            print("\nScanning {} targets...".format(len(self._targets)))
            startlen = len(self._backdoors)

            if len(args):
                ip, _, port = args[0].partition(' ')

                if valid_ip(ip) and port.isdigit(port):
                    self._targets[ip] = int(port)
                    self._scan(ip, port)
                    print(colorama.Fore.CYAN + "\n[+]" + colorama.Fore.RESET + " Scan complete - " + colorama.Style.BRIGHT + "1" + colorama.Style.NORMAL + " backdoor(s) found\n")
                else:
                    error("invalid IP address or port number")
            else:
                if len(self._targets):
                    for ip, port in self._targets.items():
                        self._scan(ip, port)
                    print(colorama.Fore.CYAN + "\n[+]" + colorama.Fore.RESET + " Scan complete - " + colorama.Style.BRIGHT + str(len(self._backdoors) - startlen) + colorama.Style.NORMAL + " backdoor(s) found\n")
                else:
                    error("no targets to scan")
                    self.help()

            self._save()

        except KeyboardInterrupt:
            return
        except Exception as e:
            debug(str(e)) 
Example #25
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def help(self, *args):
        """
        Show usage information

        """
        print('\n' + colorama.Fore.YELLOW + colorama.Style.BRIGHT + '   COMMAND             DESCRIPTION' + colorama.Fore.RESET + colorama.Style.NORMAL)
        print('   search           ' + colorama.Style.DIM + '   query the Shodan IoT search engine for targets' + colorama.Style.NORMAL)
        print('   scan [ip]        ' + colorama.Style.DIM + '   scan target host(s) for backdoors' + colorama.Style.NORMAL)
        print('   map [ip]         ' + colorama.Style.DIM + '   map local network(s) of vulnerable routers' + colorama.Style.NORMAL)
        print('   pharm <dns>      ' + colorama.Style.DIM + '   modify the dns server of vulnerable routers' + colorama.Style.NORMAL)
        print('   targets          ' + colorama.Style.DIM + '   show current targets' + colorama.Style.NORMAL)
        print('   backdoors        ' + colorama.Style.DIM + '   show backdoors detected this sessions' + colorama.Style.NORMAL)
        print('   devices          ' + colorama.Style.DIM + '   show devices connected to backdoored routers'+ colorama.Style.NORMAL)
        print('   exit/quit        ' + colorama.Style.DIM + '   end session and exit program\n' + colorama.Style.NORMAL) 
Example #26
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def targets(self, *args):
        """
        Show all target hosts

        """
        pprint.pprint(self._targets)
        print(colorama.Fore.GREEN + '\n[+] ' + colorama.Style.BRIGHT + colorama.Fore.RESET + str(len(self._targets)) + colorama.Style.NORMAL + ' targets ready to scan\n') 
Example #27
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def devices(self, *args):
        """
        Show all discovered devices connected to vulnerable routers

        """
        pprint.pprint(self._devices)
        print(colorama.Fore.CYAN + '\n[+] ' + colorama.Style.BRIGHT + colorama.Fore.RESET + str(len(self._devices)) + colorama.Style.NORMAL + ' devices connected to vulnerable routers\n') 
Example #28
Source File: util.py    From knack with MIT License 5 votes vote down vote up
def __init__(self, message, color):
        import colorama
        self._message = message
        self._color = getattr(colorama.Fore, color.upper(), None) 
Example #29
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def warn(msg, color='YELLOW'):
    print ('\n' + getattr(colorama.Fore, color)  + colorama.Style.BRIGHT + '[!] ' + colorama.Fore.WHITE + 'Warning - ' + colorama.Style.NORMAL + msg + '\n') 
Example #30
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def info(msg, color='GREEN'):
    print (getattr(colorama.Fore, color)  + colorama.Style.BRIGHT + '[+] ' + colorama.Fore.WHITE + colorama.Style.NORMAL  + msg)