Tor Stem API

Tor Stem Controller

Just in case somebody out there is looking for an example of how to use Tor’s Stem API, here is a tiny Python script that allows the user to monitor circuit connections. Here, I’m just getting basic information like description, nickname, and address, but the API docs show much more information that you can get. Just be mindful that you will need to change the string within the authenticate method. You can find your own hash by running, if I remember correctly, cat ~/.tor/torrc.

from stem import CircStatus
from stem import CircPurpose
from stem import Signal
from stem.control import Controller

#Connect to control socket on TOR with specified port number
with Controller.from_port(port = 9051) as controller:
    controller.authenticate('16:E0BD65E652CA0F2A60283C691B131B3ED08BA824F10AA484AB6EEE71CC')
    controller.signal(Signal.NEWNYM)

    #Get list of active circuits
    for circuit in controller.get_circuits():

        #Filter circuit status since FAILED/CLOSED are not of interest. Same for purpose being general
        if circuit.purpose == CircPurpose.GENERAL and circuit.status == CircStatus.BUILT:

            #List tuples of the node fingerprint, nickname, and IP address and print them to CL
            relay_fingerprints = [(desc.fingerprint, desc.nickname, desc.address) for desc in controller.get_network_statuses()]
            for node in relay_fingerprints:
                try:
                  print(node[0], node[1], node[2])
                except Exception as exc:
                  print('%s => %s' % (node, exc))

#Some coding assistance from https://stem.torproject.org/tutorials/to_russia_with_love.html

Tor Stem API

comments powered by Disqus