Skip to content

Latest commit

 

History

History
165 lines (119 loc) · 6.05 KB

File metadata and controls

165 lines (119 loc) · 6.05 KB

colorama

A tiny cross-platform library that makes ANSI color escape codes work everywhere — including Windows terminals — for simple, dependency-light colored output.

Overview

colorama translates ANSI SGR sequences so the same colored-output code runs on Linux, macOS, and Windows cmd/PowerShell. It exposes Fore, Back, and Style constants and can auto-reset colors after each print. When you want lightweight status coloring in a script without pulling in a larger library like Rich, colorama is the classic minimal choice.

Installation

pip install colorama

Basic Usage

from colorama import Fore, Style, init

init(autoreset=True)          # required on Windows; harmless elsewhere

print(Fore.GREEN + "[+] port 22 open")
print(Fore.RED + "[-] port 443 filtered")
print(Fore.YELLOW + Style.BRIGHT + "[!] service version disclosed")
print("normal text again")    # autoreset restored the default

Colorama's job is small and specific: make ANSI colour codes work on Windows terminals as they already do on Unix.

Important APIs

API Purpose
init(autoreset=True) Enable ANSI translation; reset style after each print
init(strip=None, convert=None) Force or disable stripping and conversion
deinit() Restore the original stdout/stderr
Fore.RED/GREEN/YELLOW/BLUE/CYAN/MAGENTA/WHITE/BLACK Foreground colour
Back.<COLOUR> Background colour
Style.BRIGHT / DIM / NORMAL Intensity
Style.RESET_ALL Clear all styling
Fore.RESET, Back.RESET Clear one attribute

Without autoreset=True you must append Style.RESET_ALL yourself, or the styling bleeds into subsequent output.

Example

Color-coded status messages:

from colorama import Fore, Style, init

init(autoreset=True)   # reset color after each print; enables ANSI on Windows

print(Fore.GREEN + "[+] Host 192.168.56.10 is up")
print(Fore.RED   + "[-] Port 3389 (RDP) exposed")
print(Fore.YELLOW + "[!] TLS 1.0 still enabled")
print("normal text, color already reset")

Output

[+] Host 192.168.56.10 is up
[-] Port 3389 (RDP) exposed
[!] TLS 1.0 still enabled
normal text, color already reset

A reusable status-logger helper:

from colorama import Fore, Style, init

init(autoreset=True)

def log(level, msg):
    tag = {
        "ok":   Fore.GREEN + "[+]",
        "warn": Fore.YELLOW + "[!]",
        "err":  Fore.RED + "[-]",
    }[level]
    print(f"{tag}{Style.RESET_ALL} {msg}")

log("ok", "SSH reachable")
log("warn", "Anonymous FTP allowed")
log("err", "SMB signing disabled")

Output

[+] SSH reachable
[!] Anonymous FTP allowed
[-] SMB signing disabled

Highlight matches while parsing a log file:

from colorama import Fore, init

init(autoreset=True)

lines = ["GET /index.html 200", "POST /login 401", "GET /admin 403"]
for line in lines:
    if " 401" in line or " 403" in line:
        print(Fore.RED + line)
    else:
        print(Fore.GREEN + line)

Output

GET /index.html 200
POST /login 401
GET /admin 403

Security Use Cases

  • Status highlighting — color success/warning/error lines in scanners and enumeration scripts for fast triage.
  • Cross-platform tooling — ship one colored-output script that works on both a Kali box and a Windows agent.
  • Log analysis — highlight suspicious status codes, failed logins, or IOCs while streaming through log files.
  • Lightweight CLIs — add readability to small tools without the footprint of a full TUI library.
  • Report emphasis — draw the operator's eye to high-severity findings in terminal output.

Common Mistakes

  • Forgetting init() — colours appear as raw escape sequences on Windows.
  • Omitting autoreset=True and then forgetting Style.RESET_ALL, so every later line inherits the colour.
  • Colouring output that gets redirected — escape codes end up in files and break parsing. Check sys.stdout.isatty().
  • Relying on colour alone to convey meaning, which fails for colour-blind users and in monochrome logs. Pair it with a symbol or word.
  • Interpolating untrusted data into a coloured string without stripping escape sequences.
  • Reaching for colorama when [[Rich]] is already a dependency — Rich handles this and much more.

Security Considerations

[!warning] Strip escape sequences from untrusted output A banner or log line from a target can contain ANSI escapes.

  • Terminal escape injection is a real issue. Untrusted content containing escape sequences can move the cursor, clear the screen, or overwrite previously printed lines — letting a hostile target hide findings from an analyst reading the output. Strip control characters from anything you did not generate.
  • Colour codes corrupt redirected output. A findings file full of escape sequences is hard to parse and easy to misread; disable styling when stdout is not a TTY.
  • Never use colour as the only signal. Accessibility aside, logs are read in monochrome far more often than people expect.
  • Keep diagnostics on stderr and data on stdout so colourised progress never contaminates results.
  • Colorama is presentation only — it has no security function, and adding it to a tool changes nothing about how safely that tool handles data.

Best Practices

  • Call init(autoreset=True) once at startup so you don't leak color state into later output.
  • Use Style.RESET_ALL explicitly when building strings you don't print immediately.
  • Reach for colorama when you only need color; use [[Rich]] for tables, progress bars, and layout.
  • Avoid color when output is redirected to a file (check sys.stdout.isatty()), or strip codes for logs.
  • Keep a small semantic palette (green/yellow/red) consistent across your tools.

References

Related Topics

  • [[Rich]] — richer output when you outgrow simple coloring
  • [[tqdm]] — pair colored status with progress bars
  • [[Readme|Python for Security Professionals]] — course home