general socks server failure when switching identity using stem

  • Last Update :
  • Techknowledgy :

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)

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) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

Suggestion : 2

Even though you use tor some website are anycodings_tor looking for User Agent. Try to had User anycodings_tor Agent header to your request. I had the anycodings_tor same problem.,I would like to use tor from python to anycodings_tor automate requests. I made a test with a page anycodings_tor to check IP and it works.,Which things I am missing to query from anycodings_tor python instead than from browser?,I then pointed to the site I want to, and anycodings_tor apparently they avoid a tor endpoint because anycodings_tor (see stack trace below) - but it works from anycodings_tor tor browser.

This worked for me

from urllib.request
import Request, urlopen
from bs4
import BeautifulSoup
import random
from fake_useragent
import UserAgent
from torrequest
import TorRequest
import time, socks, socket
from stem
import Signal
from stem.control
import Controller

ua = UserAgent()

with Controller.from_port(port = 9051) as controller:
   controller.authenticate(password = 'YourPasswordHere')
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

controller.signal(Signal.NEWNYM)
if controller.is_newnym_available() == False:
   print("Waitting time for Tor to change IP: " + str(controller.get_newnym_wait()) + " seconds")
time.sleep(controller.get_newnym_wait())
req = Request(url)
req.add_header('User-Agent', ua.random)
req_doc = urlopen(req) #.read().decode('utf8')
print(req_doc)

Suggestion : 3

A SOCKS proxy is a proxy server at the TCP level. In other words, it acts as a tunnel, relaying all traffic going through it without modifying it. SOCKS proxies can be used to relay traffic using any network protocol that uses TCP.,This Python module allows you to create TCP connections through a SOCKS proxy without any special effort. It also supports relaying UDP packets with a SOCKS5 proxy.,Connection will take a bit longer to allow negotiation with the proxy server. Please note that calling connect without calling set_proxy earlier will connect without a proxy (just like a regular socket).,PySocks lets you send traffic through SOCKS and HTTP proxy servers. It is a modern fork of SocksiPy with bug fixes and extra features.

Installation

pip install PySocks

Or download the tarball / git clone and...

python setup.py install

socks.socksocket

import socks

s = socks.socksocket() # Same API as socket.socket in the standard lib

s.set_proxy(socks.SOCKS5, "localhost") # SOCKS4 and SOCKS5 use port 1080 by
default
# Or
s.set_proxy(socks.SOCKS4, "localhost", 4444)
# Or
s.set_proxy(socks.HTTP, "5.5.5.5", 8888)

# Can be treated identical to a regular socket object
s.connect(("www.somesite.com", 80))
s.sendall("GET / HTTP/1.1 ...")
print s.recv(4096)

Example use case with the sockshandler urllib2 handler. Note that you must import both socks and sockshandler, as the handler is its own module separate from PySocks. The module is included in the PyPI package.

import urllib2
import socks
from sockshandler
import SocksiPyHandler

opener = urllib2.build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050))
print opener.open("http://www.somesite.com/") # All requests made by the opener will pass through the SOCKS proxy

First load the socks module with the command:

>>>
import socks
   >>>