Doing netstat queries means that I get 80000+ ip addresses on my server. Each of these addresses I would have to check against the list of relays to sort out connections to other relays and only do GETINFO ip-to-country to the remaining IPs. This sounds complicated and error-prone.
Not really. Does this do the trick?
========================================
from stem.control import Controller from stem.util import system
TOR_PID = "3470" # fill this in!
def get_tor_connections(): """ Provides the (ip address, port) tuples for tor's connections. """
results = [] netstat_output = system.call("netstat -np") established_entry = "ESTABLISHED %s/tor" % TOR_PID
for line in netstat_output: if established_entry in line: ip, port = line.split()[4].split(':') results.append((ip, port))
return results
with Controller.from_port(control_port = 9051) as controller: controller.authenticate() relay_ips = set([desc.address for desc in controller.get_network_statuses()])
for ip, port in get_tor_connections(): if ip not in relay_ips: locale = controller.get_info('ip-to-country/%s' % ip) print 'exit connection to %s' % locale