Stem as python tor client - stuck on loading descr

2019-07-04 22:07发布

I'm trying to connect to tor with python stem, while trying to connect (using th emodified example) it just won't work...here's my code: (I'm using python 3.4.1)

import socket,urllib, sys, socks, stem.process
from stem.util import term    

SOCKS_PORT = 7000

# Set socks proxy and wrap the urllib module

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT) socket.socket = socks.socksocket

# Perform DNS resolution through the socket

def getaddrinfo(*args):   return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]

socket.getaddrinfo = getaddrinfo


def query(url):   """   Uses urllib to fetch a site using SocksiPy for Tor over the SOCKS_PORT.   """

  try:
    return urllib.urlopen(url).read()   except:
    return "Unable to reach %s" % url



def print_bootstrap_lines(line):   if "Bootstrapped " in line:
      print(term.format(line, term.Color.BLUE))


print(term.format("Starting Tor:\n", term.Attr.BOLD))

tor_process = stem.process.launch_tor_with_config(   tor_cmd = "C:\Users\Nadav\Desktop\Tor Browser\Tor\\tor.exe" ,   config = {
    'SocksPort': str(SOCKS_PORT),
    'ExitNodes': '{ru}',   },   init_msg_handler = print_bootstrap_lines, )

print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD)) print(term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE))

tor_process.kill

标签: python proxy tor
1条回答
神经病院院长
2楼-- · 2019-07-04 22:33

The socks port can be different from the port to manipulate tor using stem / stem.control

Hopefully this helps to get things working for you:

import requesocks as requests
from stem import Signal
from stem.control import Controller

# proxies for requests
proxies = {'http': 'socks5://127.0.0.1:9150',
       'https': 'socks5://127.0.0.1:9150'}

# when using the Controller
with Controller.from_port(port=9151) as controller:
    controller.authenticate()
    controller.signal(Signal.NEWNYM)

Notice that the port for sock is different from the port for the Controller. You can find the port for the controller in your torrc file (for me it was called torrc-defaults).

Looks something like this:

# Bind to this address to listen to connections from SOCKS-speaking
# applications.
SocksPort 9150
ControlPort 9151

Hope this helps!

查看更多
登录 后发表回答