问题:如何在 Python 中更改 Tor 身份?

我有以下脚本:

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

print(urllib2.urlopen("http://www.ifconfig.me/ip").read())

它使用 tor 和SocksiPy

现在我想改变每个请求的 tor 身份,例如:

for i in range(0, 10):
   #somehow change tor identity
   print(urllib2.urlopen("http://www.ifconfig.me/ip").read())

我怎样才能做到这一点?

解答

今天,我对这个问题进行了很多搜索,终于设法回答了自己。但在我需要说 pirvoxy 和 tor 应该正确配置之前。第一个脚本,然后是关于配置的一点点:

import urllib2
from TorCtl import TorCtl

proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
opener = urllib2.build_opener(proxy_support) 

def newId():
    conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="your_password")
    conn.send_signal("NEWNYM")

for i in range(0, 10):
    print "case "+str(i+1)
    newId()
    proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
    urllib2.install_opener(opener)
    print(urllib2.urlopen("http://www.ifconfig.me/ip").read())

上面的脚本获取新的 IP 并从 ifconfig.me 网站检查它。关于配置:我们需要Privoxy。要将 TOR 与 HTTP 连接一起使用,privoxy 应该与 tor 一起使用。我们可以通过将 thi 添加到 /etc/privoxy/config 文件来做到这一点:

forward-socks5 / localhost:9050 . #dot is important at the end

然后我们在 /etc/tor/torrc 文件中配置 ControlPort。我们只需要取消注释这一行:

ControlPort 9051
## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4C

然后我们只需重新启动tor:

/etc/init.d/tor restart
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐