这是茎教程的工作版本,该茎茎教程使用了
pysocks它及其
sockshandler模块以避免猴子修补套接字模块:
#!/usr/bin/env python"""https://stem.torproject.org/tutorials/to_russia_with_love.htmlUsage: russian-tor-exit-node [<tor>] [--color] [--geoipfile=</path/to/file>] russian-tor-exit-node -h | --help russion-tor-exit-node --versionDependencies:- tor (packaged and standalone executables work)- pip install stem- pip install PySocks- pip install docopt : parse options- pip install colorama : cross-platform support for ANSI colors- [optional] sudo apt-get tor-geoipdb : if tor is bundled without geoip files; --geoipfile=/usr/share/tor/geoip"""import sysfrom contextlib import closingimport colorama # $ pip install coloramaimport docopt # $ pip install docoptimport socks # $ pip install PySocksimport stem.process # $ pip install stemfrom sockshandler import SocksiPyHandler # see pysocks repositoryfrom stem.util import termtry: import urllib2except importError: # Python 3 import urllib.request as urllib2args = docopt.docopt(__doc__, version='0.2')colorama.init(strip=not (sys.stdout.isatty() or args['--color']))tor_cmd = args['<tor>'] or 'tor'socks_port = 7000config = dict(SocksPort=str(socks_port), ExitNodes='{ru}')if args['--geoipfile']: config.update(GeoIPFile=args['--geoipfile'], GeoIPv6File=args['--geoipfile']+'6')def query(url, opener=urllib2.build_opener( SocksiPyHandler(socks.PROXY_TYPE_SOCKS5, "localhost", socks_port))): try: with closing(opener.open(url)) as r: return r.read().depre('ascii') except EnvironmentError as e: return "Unable to reach %s: %s" % (url, e)# Start an instance of Tor configured to only exit through Russia. This prints# Tor's bootstrap information as it starts. Note that this likely will not# work if you have another Tor instance running.def print_bootstrap_lines(line): if "Bootstrapped " in line: print(term.format(line, term.Color.BLUE)) else: print(line)print(term.format("Starting Tor:n", term.Attr.BOLD))tor_process = stem.process.launch_tor_with_config( tor_cmd=tor_cmd, config=config, init_msg_handler=print_bootstrap_lines,)try: print(term.format("nChecking our endpoint:n", term.Attr.BOLD)) print(term.format(query("https://icanhazip.com"), term.Color.BLUE))finally: if tor_process.poll() is None: # still running tor_process.terminate() # stops tor tor_process.wait()它可以在我的Ubuntu计算机上同时在Python 2和3上运行。
strace显示数据和DNS请求是通过Tor代理发出的。



