Changing TOR IP address with Python

Back in the 1990s, the internet was a dangerous place where network traffic was mostly unencrypted and traceable, allowing hackers to launch man-in-the-middle attacks and steal personal information quickly. To address this problem, a group of experts from the United States Naval Research Laboratory launched The Onion Routing (TOR) project, which aims to anonymize and encrypt internet connections.

Changing TOR IP address with Python methodology

TOR uses a distributed trust mechanism to safeguard your network traffic across the internet. It’s a mechanism in which many companies encrypt your data to provide layered data protection (like an Onion). So, unless all of the people involved in the encryption can be hijacked, your data will be safe. TOR chooses three separate relays, each run by a different entity, to encrypt and route your network traffic before reaching its final destination.

If you use TOR in a Python script, you may need to renew your IP address. We’ll use the stem package to modify our IP address in this tutorial. To communicate with TOR, we will utilize the torrc TOR controller file. Tor Network can be used to send requests with a different IP address. You can use it in requests.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>proxy = {
    'http':  'socks5://127.0.0.1:9050',
    'https': 'socks5://127.0.0.1:9050',
}

r = requests.get(url, proxies=proxy)  # using the TOR network</pre>
</div>

And here’s some basic working code. To get an IP address as text, we use http://codeunderscored.com.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import requests

proxy = {
    'http':  'socks5://127.0.0.1:9050',
    'https': 'socks5://127.0.0.1:9050',
}

url = 'https://codeunderscored.com'

r = requests.get(url, proxies=proxy)  # using the TOR network
print('   Tor IP:', r.text)

r = requests.get(url)
print('direct IP:', r.text)</pre>
</div>

Install TOR on your computer

Before starting this guide, we’ll assume that you’ve installed Tor and that tor services are running on port 9050 on your machine.

Tor will usually always utilize the same IP address. However, if you want to modify Tor’s IP address, you must restart or reload it. Alternatively, you might change the ControlPort (typically 9051) and Password in Tor’s settings (on Linux, in the /etc/tor/torrc file). Then, you can alter Tor’s IP address by delivering a signal with a socket.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import socket

s = socket.socket()
s.connect(('127.0.0.1', 9051))
s.send('AUTHENTICATE "your_passord"\r\nSIGNAL NEWNYM\r\n'.encode())</pre>
</div>

Alternatively, you can utilize module stem to accomplish this.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>from stem import Signal
from stem.control import Controller

with Controller.from_port(port=9051) as controller:
    controller.authenticate(password='your_password')
    controller.signal(Signal.NEWNYM)</pre>
</div>

On Linux, you can also use the netcat application in the terminal.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>printf 'AUTHENTICATE "password"\r\nSIGNAL NEWNYM\r\n' | nc 127.0.0.1 9051</pre>
</div>

You may also test IP using.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>curl https://codeunderscored.com
curl --proxy 'socks5://127.0.0.1:9050' https://codeunderscored .com</pre>
</div>

As we understand it, Tor may take a few seconds to obtain a new IP address after sending a signal. Therefore you may have to wait a few seconds before sending the subsequent request with the new IP.

Create a password

To safely use the TOR controller API, you must set a password in the tor control file torrc. Torrc can be found in the following location on a Linux system. To edit this file, you’ll need root access.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>$ ls -l /etc/tor/torrc</pre>
</div>

Hashed password generator

TOR does not keep passwords in plain text; instead, hashed passwords are stored in the torrc file. You can use the following program to produce a hashed password for Tor. It’s important to remember that the same password might be hashed to different values; therefore, use the most recently created hashed password.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>$ tor --hash-password Code#!_9PORed#D

16:160103B8D7BA7CFA605C9E99E5BB515D9AE71D33B3D01CE0E7747AD0DC</pre>
</div>

Password hashed configuration

You should save the hashed password produced above in the torrc file’s variable HashedControlPassword.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>$ sudo vi /etc/tor/torrc</pre>
</div>
<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:160103B8D7BA7CFA605C9E99E5BB515D9AE71D33B3D01CE0E7747AD0DC</pre>
</div>

Set up a STEM library

To connect with the TOR process using a control file, we will utilize the official tor project’s stem library in Python. You can use pip to install the stem library (recommended).

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>$ pip install stem</pre>
</div>

PySocks and requests installation

For communication, TOR requires a SOCKS proxy. Python’s requests package will support requesting URLs through the SOCKS protocol using PySocks.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>$ pip install requests
$ pip install pysocks</pre>
</div>

The source code

In the example below, we’ll send five calls to the httpbin’s IP address API over TOR, renewing the IP address after each request. As you can see in the output, each request generates a new TOR IP address.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>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="Code#!_9PORed#D")
        controller.signal(Signal.NEWNYM)


if __name__ == "__main__":
    for i in range(5):
        print get_current_ip()
        renew_tor_ip()
        time.sleep(5)</pre>
</div>

What Is TOR IP renewal, and how does it work?

The following function modifies the IP address of TOR. It initially authenticates with the TOR Controller API using a hashed password. Then it transmits a NEWNYM signal to the controller, who allocates it a new IP address.

Because TOR will not assign a fresh IP in such a short interval, we are snoozing the operation for 5 seconds before making the subsequent request. TOR may also assign us a previously used IP address.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>def renew_tor_ip():
    with Controller.from_port(port = 9051) as controller:
        controller.authenticate(password="Code#!_9PORed#D")
        controller.signal(Signal.NEWNYM)</pre>
</div>

Conclusion

Tor Network can be used to send requests with a different IP address. If you have Tor installed, it should operate as a service all of the time, and you can use it as a proxy server with the IP 127.0.0.1:9050. In this tutorial, we learned how to utilize the TOR controller to change the IP address in a Python program.

We also learned how to create up hashed credentials in the torrc file and use Tor’s stem API to authenticate. Though TOR provides the ability to renew IP addresses, you should not use this function, as changing IP addresses places a heavy demand on the Tor network. It also puts Tor endpoints at risk of being blacklisted by websites if misused. So, before you use the code mentioned above, keep in mind that tremendous power comes with great responsibility.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *