Tech Monger

Programming, Web Development and Computer Science.

Skip to main content| Skip to information by topic

Renew TOR IP Address from Python Script

If you are using TOR inside python script then you may find need to renew IP Address. In this tutorial we will change IP address using stem package. We will use TOR controller file torrc to communicate with TOR.


Install TOR

Before beginning with this tutorial we will assume that you have installed tor on your system and tor services are running on your machine on the port 9050.


Setup Password

To securely make use of TOR controller API you would need to setup password in tor control file torrc. On Linux system you would find torrc at following location. You would require root access to edit this file.

$ ls -l /etc/tor/torrc
-rw-r--r-- 1 root root 9628 Dec  25 15:08 /etc/tor/torrc

Generate Hashed Password

TOR does not store password in plain text, rather it store hashed password in torrc file. You can generate hashed password for the tor using following command. Note that same password can get hashed to different values, so please configure recently generated hashed password.

$ tor --hash-password MyStr0n9P#D
16:160103B8D7BA7CFA605C9E99E5BB515D9AE71D33B3D01CE0E7747AD0DC

Configure Hashed Password

Hashed password generated above should be stored inside variable HashedControlPassword of the torrc file.

$ sudo vi /etc/tor/torrc

## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:160103B8D7BA7CFA605C9E99E5BB515D9AE71D33B3D01CE0E7747AD0DC

Install STEM Library

We will use python's stem library released by official tor project to communicate with TOR process using control file. You can install stem library with pip in virtual environment (recommended).

$ pip install stem

Install Requests and PySocks

TOR requires SOCKS proxy for the communication. We will use python's requests library as it supports requesting URL with PySocks over SOCKS protocol.

$ pip install requests
$ pip install pysocks

Source Code

In below example we will make 5 requests over TOR to the httpbin's ip address API and renew IP address after each request. In output you can see we get new TOR IP address for the each request that we make.

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


def get_current_ip():
    session = requests.session()

    # TO Request URL with SOCKS over TOR
    session.proxies = {}
    session.proxies['http']='socks5h://localhost:9050'
    session.proxies['https']='socks5h://localhost:9050'

    try:
        r = session.get('http://httpbin.org/ip')
    except Exception as e:
        print str(e)
    else:
        return r.text


def renew_tor_ip():
    with Controller.from_port(port = 9051) as controller:
        controller.authenticate(password="MyStr0n9P#D")
        controller.signal(Signal.NEWNYM)


if __name__ == "__main__":
    for i in range(5):
        print get_current_ip()
        renew_tor_ip()
        time.sleep(5)
Output

{
  "origin": "199.249.230.88"
}
{
  "origin": "46.165.230.5"
}
{
  "origin": "185.220.101.53"
}
{
  "origin": "77.247.181.165"
}
{
  "origin": "195.189.96.147"
}

How Does TOR IP Renewal Works ?

Following function changes TOR IP Address. It first authenticates with TOR Controller API using previously configured hashed password. Then it sends NEWNYM singnal to the controller upon which controller assigns new IP Address. Note that we are sleeping execution for 5 seconds before making next request as TOR will not assign new IP in very short interval. Also TOR may assign us IP Address which was previously used.

def renew_tor_ip():
    with Controller.from_port(port = 9051) as controller:
        controller.authenticate(password="MyStr0n9P#D")
        controller.signal(Signal.NEWNYM)

Conclusion and Good Practice

In this tutorial we learned how we can use TOR controller to change IP address in python program. We also learned how to setup hashed credentials in torrc file and authenticate from tor's stem API. Though TOR give us ability to renew IP address, this feature should not be abused as changing IP address not only puts high load on the tor network but also could endanger tor endpoints due to potential blacklisting by sites if used in abusive way. So before you make use of above code please remember that with great power comes great responsibility.

Tagged Under : Linux Python TOR