【问题标题】:changing ip in iteration with tor python用tor python在迭代中改变ip
【发布时间】:2016-11-16 16:30:28
【问题描述】:

我想在每次循环运行时更改我的 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)

【问题讨论】:

  • 我不喜欢你的 P.S.我们在这里不提供解决方案,我们提供帮助。也许“P.S. 我正在使用 Python 3”听起来更好
  • @YotamSalmon 已编辑。对不起,如果这听起来很粗鲁。解决方案=帮助回答问题
  • Tor 每 5 分钟更改一次 ip。所以你必须考虑到这一点。
  • @Simonhow 在下面的帖子中显示不同的 IP 在循环中呢? stackoverflow.com/questions/9887505/…
  • 那么您的问题与您在评论中链接的问题有何不同?

标签: python python-3.x tor


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多