Tor Stem - To Russia With Love Connection Issues

大憨熊 提交于 2019-12-01 06:06:18

Here's a working version of the stem tutorial that uses pysocks and its sockshandler module to avoid monkey-patching the socket module:

#!/usr/bin/env python
"""
https://stem.torproject.org/tutorials/to_russia_with_love.html

Usage:
  russian-tor-exit-node [<tor>] [--color] [--geoipfile=</path/to/file>]
  russian-tor-exit-node -h | --help
  russion-tor-exit-node --version

Dependencies:

- 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 sys
from contextlib import closing

import colorama  # $ pip install colorama
import docopt  # $ pip install docopt
import socks  # $ pip install PySocks
import stem.process  # $ pip install stem
from sockshandler import SocksiPyHandler  # see pysocks repository
from stem.util import term

try:
    import urllib2
except ImportError: # Python 3
    import urllib.request as urllib2


args = docopt.docopt(__doc__, version='0.2')
colorama.init(strip=not (sys.stdout.isatty() or args['--color']))

tor_cmd = args['<tor>'] or 'tor'
socks_port = 7000
config = 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().decode('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()

It works on both Python 2 and 3 on my Ubuntu machine.

strace shows data and dns requests are made via the tor proxy.

Answer posted by @J.F.Sebastian gives error on Python 3.4, and it can be fixed, but here is working code WITH PyCurl surely like in stem example.

import pycurl
import stem.process
import io

SOCKS_PORT = 9150

print("Starting Tor:\n")

def print_bootstrap_lines(line):
  if "Bootstrapped " in line:
    print(line)

tor_process = stem.process.launch_tor_with_config(
  config = {
    'SocksPort': str(SOCKS_PORT),
    #'ExitNodes': '{au}',
  },
  init_msg_handler = print_bootstrap_lines,
)

output = io.BytesIO()

curl = pycurl.Curl()
curl.setopt( pycurl.URL, 'http://www.example.com' )
curl.setopt( pycurl.PROXY, 'localhost' )
curl.setopt( pycurl.PROXYPORT, SOCKS_PORT )
curl.setopt( pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5 )
curl.setopt( pycurl.WRITEFUNCTION, output.write)
curl.setopt(pycurl.HTTPHEADER, ['X-Requested-With: XMLHttpRequest', 'referer: http://www.meendo.net/?partner=13026'])
#curl.set_option(pycurl.USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36")
curl.setopt(pycurl.FOLLOWLOCATION, 1)

curl.perform()

print("RESULT : " + output.getvalue().decode('ascii'))

tor_process.kill()  # stops tor
output.close() # free used memory
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!