Renew Tor's IP in Python

1

I have the following code:

import requests
import time
from stem import Signal
from stem.control import Controller

def get_tor_session():
    session = requests.session()
    session.proxies = {'http':  'socks5://localhost:9050','https': 'socks5://localhost:9050'}
    return session

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

nombres=['User1','User2','User3','User4']

for nombre in nombres:
    print nombre
    renew_connection()
    session = get_tor_session()
    print(session.get("http://httpbin.org/ip").text)
    time.sleep(5)
    print ' '

With this code, what I intend is to have a different IP with each name in the names list.

The fact is that instead of getting a different ip for each name, what I get is that ' User1 ' and ' User2 ' have an IP, and ' User3 'and' User4 ', another different IP. When it would have to be a different IP for each name.

How could I get a different IP for each name?

    
asked by ImHarvol 29.10.2017 в 19:18
source

1 answer

1

The problem is that the renewal of the ip takes an indeterminate time to take place. This change is made asynchronously and meanwhile the previous id is used. The problem is that 5 seconds are not enough for this change, using the previous id for the connection.

What you can do is increase the waiting time, or something more robust like:

import requests
import time
from stem import Signal
from stem.control import Controller

def get_tor_session():
    session = requests.session()
    session.proxies = {'http':  'socks5://localhost:9050','https': 'socks5://localhost:9050'}
    return session

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

nombres=['User1','User2','User3','User4']



for nombre in nombres:
    session = get_tor_session()
    new_ip = old_ip = session.get("http://httpbin.org/ip").text
    renew_connection()
    while old_ip == new_ip:
        session = get_tor_session()
        new_ip = session.get("http://httpbin.org/ip").text
        time.sleep(5)
    old_ip = new_ip

    print(nombre)
    print(new_ip)
    
answered by 30.10.2017 / 11:59
source