Search code examples
pythontor

How can I change my tor process' endpoint in stem?


I'm using the stem to control a tor node created with stem.process.launch_tor_with_config. I've also created a stem.control.Controller that is operating on the aforementioned process' control port.

How can I change the exit node? I looked at stem.controller.Controller.new_circuit, but this appears to change the intermediate nodes, preserving the endpoint.

Does anybody know how this could be done?

Thanks!

Edit:

So I think I may be misunderstanding something fundamental, but I can't seem to wrap my head around it. I tried calling Controller.get_circuits() and found a list of CircuitEvent objects. Does this mean that a single process can handle multiple circuits? If so, how do I select one for use?

Note that I'm directing HTTP requests to through Privoxy, which in turn is forwarding it to the tor process' SOCKS port.

Edit 2:

I found something that works, but I don't know how it works, which worries me. I'll gladly award an answer to anyone who can either:

  1. Explain why my approach works
  2. Show be a better approach and explain how that works

Here's what I've done:

for circuit in controller.get_circuits():
    controller.close_circuit(circuit.id)

There it is. The external IP changed, so I know I've done something but hell if I know exactly what.


Solution

  • You have a couple options to use a specific exit...

    • Set the ExitNodes attribute in your torrc. This is exemplified in...

    https://stem.torproject.org/tutorials/to_russia_with_love.html

    • Call extend_circuit() on one of your present circuits to the desired endpoint...

    https://stem.torproject.org/api/control.html#stem.control.Controller.extend_circuit

    If the question you're trying to ask is really 'how do I get a new IP address' then that's a question we're more reluctant to answer. Partly because it's primarily for ban evasion or SEO, and partly because repeated circuit creation puts a high load on the Tor network.

    As for why your IP seems to change when you call close_circuit(), that's because Tor then needs to recreate a new circuit on your behalf for the following request. There is no guarantee that the IP will be new, and doing so involves a fair bit of traffic to telescope your connection through three fresh hops.

    I'm not often on StackOverflow so if you have further questions about scripting against Tor then I would suggest the tor-dev@ email list...

    https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-dev/

    Cheers! -Damian (stem's author)