使用 Python 通过 Tor 发出请求
- 2025-04-16 08:56:00
- admin 原创
- 21
问题描述:
我想使用 Tor 向一个网页发起多个 GET 请求。每个请求使用不同的 IP 地址。
import socks
import socket
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9150)
socket.socket = socks.socksocket
import requests
print (requests.get('http://icanhazip.com')).content
使用这个,我发出了一个请求。如何更改 IP 地址来发出另一个请求?
解决方案 1:
您的问题有两个方面 -
使用 Tor 发出请求
根据要求更新连接(在您的情况下,每次请求之后)
第 1 部分
第一个很容易用最新的(v2.10.0 以上)requests
库来实现,但需要额外requests[socks]
使用 socks 代理。
安装-
pip install requests[socks]
基本用法-
import requests
def get_tor_session():
session = requests.session()
# Tor uses the 9050 port as the default socks port
session.proxies = {'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050'}
return session
# Make a request through the Tor connection
# IP visible through Tor
session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)
# Above should print an IP different than your public IP
# Following prints your normal public IP
print(requests.get("http://httpbin.org/ip").text)
第 2 部分
要更新 Tor IP,即拥有一个新的可见出口 IP,您需要能够通过它连接到 Tor 服务ControlPort
,然后发送NEWNYM
信号。
常规 Tor 安装默认不启用此功能ControlPort
。您需要编辑torrc 文件并取消注释相应的行。
ControlPort 9051
## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:05834BCEDD478D1060F1D7E2CE98E9C13075E8D3061D702F63BCD674DE
请注意,HashedControlPassword
以上内容适用于密码"password"
。如果您想设置其他密码,请将HashedControlPassword
torrc 中的 替换为您想要设置的密码tor --hash-password "<new_password>"
。<new_password>
................................................................................
Windows 用户警告:请参阅此处的帖子。
在 Windows 上存在一个问题:如果使用以下命令安装 tor,则会忽略 torrc 文件中的控制端口设置:
tor --service install
要解决此问题,请在编辑 torrc 文件后输入以下命令:
tor --service remove
tor --service install -options ControlPort 9051
................................................................................
好的,现在我们已经正确配置了 Tor,如果 Tor 已经在运行,则必须重新启动它。
sudo service tor restart
Tor 现在应该已经在 9051 上启动并运行了,ControlPort
我们可以通过它向它发送命令。我更喜欢使用官方的 stem 库来控制 Tor。
安装 -
pip install stem
您现在可以通过调用以下函数来更新 Tor IP。
续订 IP -
from stem import Signal
from stem.control import Controller
# signal TOR for a new connection
def renew_connection():
with Controller.from_port(port = 9051) as controller:
controller.authenticate(password="password")
controller.signal(Signal.NEWNYM)
要验证 Tor 是否有新的出口 IP,只需重新运行第 1 部分中的代码。由于某些我不知道的原因,您需要创建一个新session
对象才能使用新的 IP。
session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)
解决方案 2:
这是您要使用的代码(使用下载 stem 包pip install stem
)
from stem import Signal
from stem.control import Controller
with Controller.from_port(port = 9051) as controller:
controller.authenticate(password='your password set for tor controller port in torrc')
print("Success!")
controller.signal(Signal.NEWNYM)
print("New Tor connection processed")
祝你好运,希望一切顺利。
解决方案 3:
你可以尝试纯 Python 实现的 Tor 协议Torpy。完全不需要原有的 Tor 客户端或 Stem 依赖。
$ pip3 install torpy[requests]
...
$ python3.7
>>> from torpy.http.requests import TorRequests
>>> with TorRequests() as tor_requests:
... print("build circuit")
... with tor_requests.get_session() as sess:
... print(sess.get("http://httpbin.org/ip").json())
... print(sess.get("http://httpbin.org/ip").json())
... print("renew circuit")
... with tor_requests.get_session() as sess:
... print(sess.get("http://httpbin.org/ip").json())
... print(sess.get("http://httpbin.org/ip").json())
...
build circuit
{'origin': '23.129.64.190, 23.129.64.190'}
{'origin': '23.129.64.190, 23.129.64.190'}
renew circuit
{'origin': '198.98.50.112, 198.98.50.112'}
{'origin': '198.98.50.112, 198.98.50.112'}
因此,每次你获得新的会话时,你都会获得新的身份(基本上,你会获得新的电路和新的出口节点)。更多示例请参阅 readme 文件https://github.com/torpyorg/torpy。
解决方案 4:
你可以使用torrequest
这个库(无耻的插件)。它在 PyPI 上可用。
from torrequest import TorRequest
with TorRequest() as tr:
response = tr.get('http://ipecho.net/plain')
print(response.text) # not your IP address
tr.reset_identity()
response = tr.get('http://ipecho.net/plain')
print(response.text) # another IP address, not yours
解决方案 5:
Requests从 2.10.0 版本开始支持使用 SOCKS 协议的代理。
import requests
proxies = {
'http': 'socks5://localhost:9050',
'https': 'socks5://localhost:9050'
}
url = 'http://httpbin.org/ip'
print(requests.get(url, proxies=proxies).text)
解决方案 6:
这个答案补充了 Ashish Nitin Patil 针对Windows 的答案
(请随意更新这个答案)
第 2 部分
ControlPort 9051
## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:05834BCEDD478D1060F1D7E2CE98E9C13075E8D3061D702F63BCD674DE
以上HashedControlPassword
就是密码。如果您想在控制台中设置其他密码,请导航至Tor BrowserBrowserTorBrowserTor
并输入以下命令tor.exe --hash-password password_XYZ | more
:)。它会显示类似“HashedControlPassword 16:54C092A8...
这是您的密码”的内容。现在,您可以将其添加到 torrc 文件(Tor BrowserBrowserTorBrowserDataTor orrc
)。
然后您需要重新启动 Tor:
tor --service remove
tor --service install -options ControlPort 9051
要检查该操作是否有效,netstat -an
您将看到端口 9051 已打开。
注意,这tor --service install -...
将创建Tor Win32 Service
。出于某种原因,似乎必须停止服务才能使用浏览器(运行services.msc
)。
编辑:您将在这里找到许多信息(关于端口号和代理、Tor、Privoxy、自动切换用户代理……)。
解决方案 7:
这段代码运行正常。使用 Tor,它会在每次请求后更改 IP 地址。
import time, socks, socket
from urllib2 import urlopen
from stem import Signal
from stem.control import Controller
nbrOfIpAddresses=3
with Controller.from_port(port = 9051) as controller:
controller.authenticate(password = 'my_pwd')
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
for i in range(0, nbrOfIpAddresses):
newIP=urlopen("http://icanhazip.com").read()
print("NewIP Address: %s" % newIP)
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())
controller.close()
解决方案 8:
这个非常旧requests
,requesocks
没有response.json()
很多其他的东西。
我想保持代码简洁。但是,requests
目前还不支持 socks5(更多详情,请阅读此主题https://github.com/kennethreitz/requests/pull/478)
所以我Privoxy
暂时使用它作为连接 Tor 的 http 代理。
在 Mac 上安装和配置 Privoxy
brew install privoxy
vim /usr/local/etc/privoxy/config
# put this line in the config
forward-socks5 / localhost:9050 .
privoxy /usr/local/etc/privoxy/config
在 Ubuntu 上安装并配置 Privoxy
sudo apt-get install privoxy
sudo vim /etc/privoxy/config
# put this line in the config
forward-socks5 / localhost:9050 .
sudo /etc/init.d/privoxy restart
现在我可以像使用 http 代理一样使用 Tor 了。下面是我的 Python 脚本。
import requests
proxies = {
'http': 'http://127.0.0.1:8118',
}
print requests.get('http://httpbin.org/ip', proxies=proxies).text
解决方案 9:
一个更新 IP 的好功能。Windows 示例
def renew_tor_ip():
with Controller.from_port(port = 9051) as controller:
controller.authenticate(password="aAjkaI19!!laksjd")
controller.signal(Signal.NEWNYM)
使用示例
import requests
import time
from stem import Signal
from stem.control import Controller
def get_current_ip():
session = requests.session()
# TO Request URL with SOCKS over TOR
session.proxies = {}
session.proxies['http']='socks5h://localhost:9150'
session.proxies['https']='socks5h://localhost:9150'
try:
r = session.get('http://httpbin.org/ip')
except Exception as e:
print(str(e))
else:
return r.text
#16:8EE7AEE3F32EEEEB605C6AA6C47B47808CA6A81FA0D76546ADC05F0F15 to aAjkaI19!!laksjd
#cmd shell "C:UsersArthurDesktopTor BrowserBrowserTorBrowserTor or.exe" --hash-password aAjkaI19!!laksjd | more
#Torcc config
#ControlPort 9051
#HashedControlPassword 16:8EE7AEE3F32EEEEB605C6AA6C47B47808CA6A81FA0D76546ADC05F0F15
def renew_tor_ip():
with Controller.from_port(port = 9051) as controller:
controller.authenticate(password="aAjkaI19!!laksjd")
controller.signal(Signal.NEWNYM)
for i in range(5):
print(get_current_ip())
renew_tor_ip()
time.sleep(5)
扫码咨询,免费领取项目管理大礼包!