Stem - Tor Controller Library

1.8.2 · active · verified Fri Apr 17

Stem is a Python controller library that provides a high-level API for interacting with the Tor daemon. It allows applications to query Tor's status, manage circuits and streams, and retrieve information about Tor relays. The current stable version is 1.8.2, with releases occurring as needed for bug fixes and minor enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This example connects to a running Tor daemon's control port (typically 9051) and authenticates using either an environment variable for a password or via Tor's default cookie-based authentication. It then prints the Tor version and the number of active circuits.

import stem.control
import os

# Default Tor control port is 9051. Authenticate with password or cookie.
try:
    with stem.control.Controller.from_port(port=9051) as controller:
        # Attempt authentication. If TOR_CONTROL_PASSWORD env var is set, use it.
        # Otherwise, authenticate() without arguments tries cookie authentication.
        auth_password = os.environ.get('TOR_CONTROL_PASSWORD', '')
        if auth_password:
            controller.authenticate(password=auth_password)
        else:
            controller.authenticate() # Attempts cookie authentication by default

        print("Successfully connected to Tor controller!")
        print(f"Tor version: {controller.get_version()}")
        
        # Example: Get all active circuits
        circuits = controller.get_circuits()
        print(f"Number of active Tor circuits: {len(circuits)}")

except stem.SocketClosed:
    print("Error: Could not connect to Tor's control port. Is Tor running?")
    print("Check your Tor configuration (torrc) for ControlPort and authentication settings.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →