stem_examples/src/stem_examples/connection_resolution.py

78 lines
2.7 KiB
Python
Executable File

__doc__ = """Connection Resolution
Connection information is a useful tool for learning more about network
applications like Tor. Our stem.util.connection.get_connections() function
provides an easy method for accessing this information, with a few caveats...
Connection resolvers are platform specific. We support several platforms but
not all.
By default Tor runs with a feature called DisableDebuggerAttachment. This
prevents debugging applications like gdb from analyzing Tor unless it is run as
root. Unfortunately this also alters the permissions of the Tor process /proc
contents breaking numerous system tools (including our resolvers). To use this
function you need to either run as root (discouraged) or add
DisableDebuggerAttachment 0 to your torrc.
Please note that if you operate an exit relay it is highly discouraged for you
to look at or record this information. Not only is doing so eavesdropping, but
likely also a violation of wiretap laws.
With that out of the way, how do you look up this information? Below is a
simple script that dumps Tor's present connections.
https://stem.torproject.org/tutorials/east_of_the_sun.html
"""
import os
import sys
import logging
from stem.util.connection import get_connections, system_resolvers
from stem.util.system import pid_by_name
LOG = logging.getLogger()
def iMain (lArgs=None):
resolvers = system_resolvers()
if not resolvers:
LOG.error("Stem doesn't support any connection resolvers on our platform.")
return 1
picked_resolver = resolvers[0] # lets just opt for the first
LOG.info("Our platform supports connection resolution via: %s (picked %s)" % (', '.join(resolvers), picked_resolver))
tor_pids = pid_by_name('tor', multiple = True)
if not tor_pids:
LOG.warn("Unable to get tor's pid. Is it running?")
return 1
if len(tor_pids) > 1:
LOG.info("You're running %i instances of tor, picking the one with pid %i" % (len(tor_pids), tor_pids[0]))
else:
LOG.info("Tor is running with pid %i" % tor_pids[0])
LOG.info("Connections:\n")
for conn in get_connections(picked_resolver, process_pid = tor_pids[0], process_name = 'tor'):
LOG.info(" %s:%s => %s:%s" % (conn.local_address, conn.local_port, conn.remote_address, conn.remote_port))
return 0
if __name__ == '__main__':
from stem_examples.stem_utils import vsetup_logging
if os.environ.get('DEBUG', ''):
log_level = 10
else:
log_level = 20
vsetup_logging(LOG, log_level)
try:
i = iMain(sys.argv[1:])
except KeyboardInterrupt as e:
i = 0
except Exception as e:
LOG.exception(f"Exception {e}")
i = 1
sys.exit(i)