How to control tor, when use tor proxy

て烟熏妆下的殇ゞ 提交于 2019-11-29 07:42:47
Ionut Hulub

The problem is caused by the socket.socket = socks.socksocket line.

As a temporary solution, one can keep a backup copy of socket.socket and use that to unset the proxy before asking Tor for a new identity, then set up the proxy again.

The code will look like this:

import urllib2, socks, socket
from stem import Signal
from stem.control import Controller

old_socket = socket.socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

def newI():
    socket.socket = old_socket  # don't use proxy
    with Controller.from_port(port=9051) as controller:
        controller.authenticate()
        controller.signal(Signal.NEWNYM)
    # set up the proxy again
    socket.socket = socks.socksocket

newI()

headers = {'User-Agent': 'Mozilla/3.0 (x86 [en] Windows NT 5.1; Sun)'} 
req = urllib2.Request('https://google.com', None, headers)
response = urllib2.urlopen(req)
html = response.read()

newI()

However, I am still waiting for someone to post an explanation as to why the error occurs, and a better way to fix it.

Damian

Interesting. I wonder if...

socket.socket = socks.socksocket

is causing _make_socket() to get a non-standard socket, and in turn bulk. If you use PycURL instead does it work?

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