4
votes

I want to write a simple script in Python that will connect to the TOR network and choose an exit node of some country I specify. For instance I want all my outgoing network traffic to be routed to say - spain (through the TOR network). Is there some way to achieve this?

Thanks, Tom.

2
Is there a reason you aren't just using the built in functionality for this? The torrc file can specify countries to use as exit nodes already.Robert Davey
I considered that but as far as i know the torrc file is "Hardcoded" and i have to change it and reset the connection each time i want to change my exit nodes... The problem is that i want to change my exit nodes dynamically. Let's say my python script creates 2 processes and i want one of them to have an exit node in Spain and the other in France, and they might be changed during run-time (switch exit node in runtime). Do you have an idea how i can accomplish that?Tom

2 Answers

0
votes

Ok i think i have an answer, it is not exactly what i intended but it works just as well.

I can have a more then one TOR relays on my machine and configure each one with the exit node i want in the torrc file, like Robert Davey mentioned. In my python script i can create a few processes and connect each one with a different relay - thus giving me a different exit node. An example can be found here: https://tor.stackexchange.com/questions/327/how-may-i-run-multiple-tor-relay-instances-in-a-single-linux-machine

If i want to change an exit node in an already running relay i can edit the torrc file of the relevant TOR relay and update it with the SIGHUP signal using stem python library:

from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
  controller.authenticate()
  controller.signal(Signal.HUP)
0
votes

You needn't to write a torrc file for each relay. You can launch tor passing arguments dynamically through stem. For instance:

import stem.process

tor_process = stem.process.launch_tor_with_config(
    tor_cmd = PATH_TO_TOR_LAUNCHER,
    config = {
        'SOCKSPort': str(SOCKS_PORT),
        'ControlPort': str(CTRL_PORT),
        'DataDirectory': DATA_DIR,
        'GeoIPFile': DATA_DIR + 'geoip',
        'GeoIPv6File': DATA_DIR + 'geoip6',
        'ExitNodes': '{es},{pt}'       # exiting through Spain or Portugal
        }
)

These are the country codes from the database for geolocation that Tor uses by default: http://dev.maxmind.com/geoip/legacy/codes/iso3166/