簡體   English   中英

通過 Tor 使用 Python 發出請求

[英]Make requests using Python over Tor

我想使用 Tor 向網頁發出多個 GET 請求。 我想為每個請求使用不同的 ipaddress。

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

使用這個,我提出了一個要求。 如何更改 ipaddress 以創建另一個?

您的問題有兩個方面-

  1. 使用 Tor 發出請求
  2. 根據要求更新連接(在您的情況下,在每次請求后)

第1部分

第一個很容易用最新的(v2.10.0 以上的) requests庫來實現,使用socks 代理需要額外的requests[socks]

安裝-

pip install requests 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,您需要能夠通過它的ControlPort連接到 Tor 服務,然后發送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" 如果您想設置不同的密碼,請注意tor --hash-password "<new_password>"的輸出替換 torrc 中的HashedControlPassword ,其中<new_password>是您要設置的密碼。

………………………………………………………………………………………………………………………………………………………… ……………………………………………………………………………………………………………………………………………………………………………………

Windows 用戶警告:請參閱此處的帖子。

如果使用以下命令安裝了 tor,則 Windows 上存在一個問題,其中 torrc 文件中的 controlport 設置將被忽略:

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)

這是您要使用的代碼(使用pip install stem下載 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")

祝你好運,希望能奏效。

您可以嘗試純 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'}

因此,每次當您獲得新會話時,您都會獲得新身份(基本上,您將獲得帶有新出口節點的新電路)。 在自述文件https://github.com/torpyorg/torpy 中查看更多示例

您可以使用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

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

此答案完成了適用於Windows的 Ashish Nitin Patil 之一(隨時更新此答案)

第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 Browser\\Browser\\TorBrowser\\Tor並鍵入以下命令: tor.exe --hash-password password_XYZ | more tor.exe --hash-password password_XYZ | more )。 它會給你類似HashedControlPassword 16:54C092A8...這是你的密碼。 現在您可以將它添加到 torrc 文件( Tor Browser\\Browser\\TorBrowser\\Data\\Tor\\torrc )。

然后你需要重新啟動 Tor:

tor --service remove
tor --service install -options ControlPort 9051

要檢查它是否有效,請鍵入netstat -an您現在將看到端口 9051 已打開。

請注意, tor --service install -...將創建Tor Win32 Service 出於某種原因,您似乎必須停止該服務才能使用瀏覽器(運行services.msc

編輯:你會在這里找到很多信息(關於端口號和代理、Tor、Privoxy、自動切換用戶代理......)。

這段代碼工作正常。 使用 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()

requesocksrequests非常舊,它沒有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

更新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:\Users\Arthur\Desktop\Tor Browser\Browser\TorBrowser\Tor\tor.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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM