Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

python - General SOCKS server failure when switching identity using stem

I have Tor running on a remote server (Ubuntu) on port 9150 with the control port on 9151. I've confirmed both are running via netstat -ant.

Here is my code which is eliciting the SOCKS5Error: 0x01: General SOCKS server failure error.

import socks
import socket
socks.set_default_proxy(socks.SOCKS5, server_ip, 9150)
socket.socket = socks.socksocket

I can make requests from any library and successfully get responses back with a tor ip address.

However the following is what causes the error:

from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9151) as controller:
  controller.authenticate(password)
  controller.signal(Signal.NEWNYM)

If I run the above without setting up the proxy using socks (first snippet), I can issue signals with no trouble.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...