简体   繁体   English

使用 Tor python 在迭代中更改 ip

[英]changing ip in iteration with tor python

I want to change my IP everytime I run through loop.每次运行循环时,我都想更改我的 IP。 I am trying to achieve it with TOR.我正在尝试使用 TOR 来实现它。 I have seen few posts with similar question, but solution given there is not working.我看过很少有类似问题的帖子,但给出的解决方案不起作用。 So far my code looks like:到目前为止,我的代码如下所示:

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)

I need different IP every time, instead of same IP.我每次都需要不同的IP,而不是相同的IP。

edit : I have tried using approach given on How to change Tor identity in Python?编辑:我尝试过使用如何在 Python 中更改 Tor 身份的方法? . . My limitation is not to use any external libraries.我的限制是不使用任何外部库。 also solution provided by Nedim is without external library. Nedim 提供的解决方案也没有外部库。

so far I have tried following to get different IP from mentioned link:到目前为止,我已经尝试从提到的链接中获取不同的 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)))

but it is throwing following error:但它抛出以下错误:

Error connecting to Tor control port: ConnectionRefusedError(10061, 'No connection could be made because the target machine actively refused it', None, 10061, None)
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM