General SOCKS server failure when switching identity using stem

浪子不回头ぞ 提交于 2019-11-28 11:43:21

You can't open a new controller once you've connected to Tor. Try opening a controller right at the top of your script. Then both the Tor connection and signaller use the same controller object.

This seems to work with Python3:

import time

import socket
import socks

import requests
from bs4 import BeautifulSoup
from stem import Signal
from stem.control import Controller

controller = Controller.from_port(port=9051)


def connectTor():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5 , "127.0.0.1", 9050, True)
    socket.socket = socks.socksocket


def renew_tor():
    controller.authenticate(<INSERT YOUR PASSPHRASE HERE>)
    controller.signal(Signal.NEWNYM)


def show_my_ip():
    url = "http://www.showmyip.gr/"
    r = requests.Session()
    page = r.get(url)
    soup = BeautifulSoup(page.content, "lxml")
    ip_address = soup.find("span",{"class":"ip_address"}).text.strip()
    print(ip_address)


for i in range(10):
    renew_tor()
    connectTor()
    showmyip()
    time.sleep(10)

Your first snippet is proxying traffic over tor, but Stem's Controller.from_port() method uses the socket module too. As such Stem attempts to connect to your local control port, gets proxied through a tor exit node, then can't connect.

I saw this error happens when you try to open a new connection to port 9051, while an old connection is still open. I solved the problem in this way.

#----------------Cut Here----------------------

import stem
from stem import Signal
from stem.control import Controller
from stem.connection import connect
import time
#
# Create a new controller 
#
controller = Controller.from_port()
Password = "My_Personal_Password"
#
def renew_tor():
    global controller
    global Password
    print ('Renewing Tor Circuit')
    if "stem.control.Controller" not in str(controller):
      #if global controller exist no more
      controller = Controller.from_port()
    # debug output
    print (controller)
    # authenticare the connection with the server control port 
    controller.authenticate(Password)
    print ('Tor running version is : %s' % controller.get_version() )
    # force a new circuit
    controller.signal(Signal.NEWNYM)
    # wait for new circuit
    time.sleep(10)
    print ('New Tor circuit estabilished')

if __name__ == "__main__":
    for i in range (10000):
      print ( " Attempt n. : %i " % i)  
      renew_tor()


#----------------Cut Here(end)--------------------------------------------

From your personal password you can create a hash with the command

tor --hash password My_Personal_Password

and the resulting string has the format

16:CA850F5648.........

This must be inserted in the file /etc/tor/torrc

under:

HashedControlPassword 16: CA850F5648 .........

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