用tor python

时间:2016-11-16 16:30:29

标签: python python-3.x tor

我希望每次运行循环时都更改我的IP。我试图通过TOR来实现它。我看过很少有类似问题的帖子,但是那里的解决方案没有用。到目前为止,我的代码看起来像:

import socks
#import socket
import requests
import time


for i in range(1,3):
    socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
    try:
        print (requests.get("http://icanhazip.com").text)
    except Exception as e:
        time.sleep(30)
        print (type(e))
        print (e)

我每次都需要不同的IP,而不是相同的IP。

编辑:我尝试使用How to change Tor identity in Python?上给出的方法。我的限制是不使用任何外部库。 Nedim提供的解决方案也没有外部库。

到目前为止,我一直试图通过以下链接获取不同的IP:

import socket
import sys
import os

try:
    tor_c = socket.create_connection(("127.0.0.1", 9051 ))

    secret = os.urandom(32) # pass this to authenticate
    hash = tor_c.s2k_gen(secret) # pass this to Tor on startup.

    tor_c.send('AUTHENTICATE "{}"\r\nSIGNAL NEWNYM\r\n'.format(hash))
    response = tor_c.recv(1024)
    if response != '250 OK\r\n250 OK\r\n':
        sys.stderr.write('Unexpected response from Tor control port: {}\n'.format(response))
except Exception as e:
    sys.stderr.write('Error connecting to Tor control port: {}\n'.format(repr(e)))

但它引发了以下错误:

Error connecting to Tor control port: ConnectionRefusedError(10061, 'No connection could be made because the target machine actively refused it', None, 10061, None)

1 个答案:

答案 0 :(得分:1)

def renew_connection():
    with Controller.from_port(port=9051) as controller:
        controller.authenticate(password='password')
        controller.signal(Signal.NEWNYM)
        controller.close()

def request_tor(url, headers):

    print((requests.get(url,proxies={'http': 'socks5h://localhost:9050'}, headers=headers)).text)
    r = requests.get(url)
    print('direct IP:', r.text)


if __name__ == "__main__":
    url = 'http://icanhazip.com'
    headers = { 'User-Agent': UserAgent().random }
    for i in range(5):
        request_tor(url,headers)
        renew_connection()
        time.sleep(5)