3.9 PYTHON, TOR SOCKS5 & STEM AUTOMATION 10 REAL-TIME EXAMPLES

Automate Tor HTTP requests over socks5h://, control circuits and NEWNYM signals via Stem, enforce rate limits and retries, and audit reliability for CTI collection.

๐Ÿ Programmatic Tor Automation with SOCKS5h and Stem

Automating dark web intelligence collection in Python combines SOCKS5h proxy routing (ensuring hostname/.onion resolution happens remotely inside Tor rather than leaking DNS locally) with Stem (Tor's Python control-port library for inspecting circuits, signaling NEWNYM, and managing daemon state). Reliable automation also requires cooldown pacing, retry/timeout handling, polite request throttling, and strict operational guardrails.

1. Example 1: SOCKS5h Proxy Configuration with requests
Configure a Python requests session to use socks5h://127.0.0.1:9050 so DNS lookups and .onion names resolve over Tor rather than leaking locally.
Python (requests_socks5h.py)
import requests

def make_tor_session(socks_port: int = 9050) -> requests.Session:
    session = requests.Session()
    proxy_url = f"socks5h://127.0.0.1:{socks_port}"
    session.proxies = {"http": proxy_url, "https": proxy_url}
    session.headers.update({"User-Agent": "CTI-Collector/1.0"})
    return session

sess = make_tor_session(9050)
print("Configured SOCKS5h Session:", sess.proxies)
Output: Configured SOCKS5h Session: {'http': 'socks5h://127.0.0.1:9050', 'https': 'socks5h://127.0.0.1:9050'}
2. Example 2: Stem ControlPort Authentication & Version Check
Connect to Tor's ControlPort (default 9051) using stem.control.Controller, authenticate, and query the running Tor daemon version safely.
Python (stem_version_check.py)
from stem.control import Controller

def get_tor_version(port: int = 9051) -> str:
    try:
        with Controller.from_port(address="127.0.0.1", port=port) as ctrl:
            ctrl.authenticate()
            return str(ctrl.get_version())
    except Exception as exc:
        return f"Unavailable ({exc})"

print("Tor Daemon Version:", get_tor_version(9051))
Output: Tor Daemon Version: Unavailable (SocketError)
3. Example 3: Cooldown-Aware NEWNYM Circuit Rotation
Enforce a minimum cooldown interval (such as 10+ seconds) before sending Signal.NEWNYM so scripts avoid rate-limiting or excessive circuit churn.
Python (newnym_cooldown.py)
import time
from stem import Signal
from stem.control import Controller

class CircuitRotator:
    def __init__(self, cooldown_sec: float = 10.0):
        self.cooldown_sec = cooldown_sec
        self.last_signal_ts = 0.0

    def can_rotate(self, now_ts: float) -> bool:
        return (now_ts - self.last_signal_ts) >= self.cooldown_sec

    def request_new_circuit(self, now_ts: float, port: int = 9051) -> str:
        if not self.can_rotate(now_ts):
            wait_left = round(self.cooldown_sec - (now_ts - self.last_signal_ts), 1)
            return f"SKIPPED (Cooldown active: wait {wait_left}s)"
        try:
            with Controller.from_port(port=port) as ctrl:
                ctrl.authenticate()
                ctrl.signal(Signal.NEWNYM)
            self.last_signal_ts = now_ts
            return "SIGNALED NEWNYM"
        except Exception as exc:
            return f"ERROR ({exc})"

rotator = CircuitRotator(cooldown_sec=10.0)
print("Attempt 1:", rotator.request_new_circuit(100.0))
print("Attempt 2:", rotator.request_new_circuit(104.5))
Output: Attempt 1: ERROR (SocketError) Attempt 2: SKIPPED (Cooldown active: wait 5.5s)
4. Example 4: Bounded Retries & Backoff for Tor Latency
Wrap network fetches with explicit timeouts and bounded retry/backoff logic so transient circuit stalls or slow .onion rendezvous handshakes do not hang pipelines indefinitely.
Python (bounded_retry_fetch.py)
def fetch_with_retry(target_url: str, max_attempts: int = 3, timeout_sec: int = 20) -> dict:
    attempts_used = 0
    for attempt in range(1, max_attempts + 1):
        attempts_used = attempt
        # Simulated transient timeout on first attempt, success on second
        succeeded = (attempt >= 2)
        if succeeded:
            return {"url": target_url, "status": 200, "attempts": attempts_used, "timeout": timeout_sec}
    return {"url": target_url, "status": None, "attempts": attempts_used, "timeout": timeout_sec}

print(fetch_with_retry("http://example.onion/status", max_attempts=3, timeout_sec=20))
Output: {'url': 'http://example.onion/status', 'status': 200, 'attempts': 2, 'timeout': 20}
5. Example 5: Polite Request Pacing & Rate-Limit Guard
Pace automated requests with a configurable minimum delay between fetches so collectors respect target load and avoid overwhelming volunteer relays or hidden services.
Python (polite_pacer.py)
class PolitePacer:
    def __init__(self, min_interval_sec: float = 2.0):
        self.min_interval_sec = min_interval_sec
        self.last_req_ts = None

    def check_delay(self, now_ts: float) -> float:
        if self.last_req_ts is None:
            self.last_req_ts = now_ts
            return 0.0
        elapsed = now_ts - self.last_req_ts
        sleep_needed = max(0.0, round(self.min_interval_sec - elapsed, 2))
        self.last_req_ts = now_ts + sleep_needed
        return sleep_needed

pacer = PolitePacer(min_interval_sec=2.0)
print("Req 1 sleep:", pacer.check_delay(10.0), "s")
print("Req 2 sleep:", pacer.check_delay(10.5), "s")
Output: Req 1 sleep: 0.0 s Req 2 sleep: 1.5 s
6. Example 6: Active Circuit Inspection via Stem
Query built circuits from Stem's controller to inspect hop counts and circuit IDs during debugging or health checks.
Python (stem_list_circuits.py)
from stem.control import Controller

def list_built_circuits(port: int = 9051) -> list[str]:
    try:
        with Controller.from_port(port=port) as ctrl:
            ctrl.authenticate()
            return [f"{c.id} (hops={len(c.path)})" for c in ctrl.get_circuits() if c.status == "BUILT"]
    except Exception as exc:
        return [f"ControlPort unavailable ({exc})"]

print("Built Circuits:", list_built_circuits(9051))
Output: Built Circuits: ['ControlPort unavailable (SocketError)']
7. Example 7: Response Size Cap & Content-Type Guard
Enforce maximum response byte limits and expected content types in automation scripts to guard against oversized payloads or unexpected binary responses.
Python (response_size_guard.py)
def validate_response(content_type: str, byte_len: int, max_bytes: int = 1_048_576) -> str:
    if byte_len > max_bytes:
        return f"REJECTED (Size {byte_len}B exceeds limit {max_bytes}B)"
    if not content_type.startswith(("text/", "application/json")):
        return f"REJECTED (Unexpected Content-Type: {content_type})"
    return f"ACCEPTED ({content_type}, {byte_len}B)"

print("Check 1:", validate_response("text/html; charset=utf-8", 24500))
print("Check 2:", validate_response("application/octet-stream", 5_000_000))
Output: Check 1: ACCEPTED (text/html; charset=utf-8, 24500B) Check 2: REJECTED (Unexpected Content-Type: application/octet-stream)
8. Example 8: Target Allowlist & Scheme Validation
Validate target URLs before requesting themโ€”ensuring schemes are http/https and checking against an explicit allowlist or scope rule.
Python (target_scope_validator.py)
from urllib.parse import urlparse

def is_target_allowed(url: str, allowed_hosts: set[str]) -> bool:
    parsed = urlparse(url)
    host = (parsed.hostname or "").lower()
    return parsed.scheme in ("http", "https") and host in allowed_hosts

scope = {"r6j52r5p6j32q3u6y32k4q6f4d3s2a1z9x8c7v6b5n4m3l2k1j0h9g8d.onion"}
print("Allowed:", is_target_allowed("http://r6j52r5p6j32q3u6y32k4q6f4d3s2a1z9x8c7v6b5n4m3l2k1j0h9g8d.onion/feed", scope))
print("Blocked:", is_target_allowed("http://unlisted-host.onion/feed", scope))
Output: Allowed: True Blocked: False
9. Example 9: Structured Automation Run Summary Logger
Emit a concise JSON summary at the end of each automation runโ€”recording targets checked, successes, errors, and runtimeโ€”for observability and auditing.
Python (run_summary_logger.py)
import json

run_summary = {
    "run_id": "TOR-AUTO-20261128-01",
    "targets_checked": 6,
    "succeeded": 5,
    "errors": 1,
    "proxy": "socks5h://127.0.0.1:9050"
}

print(json.dumps(run_summary, indent=2))
Output: { "run_id": "TOR-AUTO-20261128-01", "targets_checked": 6, "succeeded": 5, "errors": 1, "proxy": "socks5h://127.0.0.1:9050" }
10. Example 10: Safe Automation & Scope Compliance Gate
Verify that Python Tor automation scripts use socks5h://, respect rate limits and timeouts, avoid unauthorized probing or aggressive scanning, and follow organizational policy.
Python (automation_compliance_gate.py)
gate = {
    "uses_socks5h_remote_dns": True,
    "timeouts_and_pacing_enabled": True,
    "authorized_scope_and_passive_collection": True,
    "no_aggressive_scanning_or_abuse": True
}

print("Automation Compliance Gate:", "APPROVED" if all(gate.values()) else "HOLD")
Output: Automation Compliance Gate: APPROVED