2

I want to change my IP everytime I run through loop. I am trying to achieve it with 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.

edit : I have tried using approach given on How to change Tor identity in Python?. My limitation is not to use any external libraries. also solution provided by Nedim is without external library.

so far I have tried following to get different IP from mentioned link:

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)
Community
  • 1
  • 1
Bhavesh Ghodasara
  • 1,981
  • 2
  • 15
  • 29

1 Answers1

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)

Lashgari
  • 41
  • 11