This browser does not support JavaScript

Step-by-Step Guide on Using Python and Tor to Change Your IP Address

Post Time: 2024-11-29 Update Time: 2025-01-15

Tor (The Onion Router) is one of the most powerful tools for anonymous browsing, scraping, and bypassing IP restrictions. For better anonymity to minimize the blocked possibility, users usually also need to rotate IP addresses frequently.

This article will guide you step-by-step on how to change IPs in Tor using Python, covering the setup process, coding examples, and best practices for safety and efficiency. We hope this article is helpful to you to make the most of this combination. Let's get started!

Using Python and Tor to Change Your IP Address

What Is Tor and How Does It Work?

Tor(The Onion Router) is a privacy-focused network. It can anonymize your internet traffic by routing it through a series of volunteer-operated servers called nodes. Each time your traffic passes through these nodes, your IP address appears as if from a different location, masking your real identity.

The Tor network is widely used for:

  • Anonymizing online activity
  • Bypassing regional restrictions
  • Enhancing privacy when browsing the web

Tor usually automatically assigns a new IP address when you connect. With some extra configuration and Python scripting, you can take control and request new IP addresses programmatically whenever needed. Especially useful for tasks like web scraping.

Why Use Python to Change IP Address with Tor?

Integrating Tor with Python can automate the process of changing IP addresses, saving your time and effort. Particularly useful for tasks like web scraping, testing applications, and enhancing privacy on sensitive projects.

1. Anonymity: Hide your real IP, and websites can hardly track your activities.

2. Control: Programmatically request new IP addresses whenever required.

3. Automation: Python’s libraries make it simple to control and automate Tor’s functionality without manual intervention, including IP rotation.

4. Cost-Effective: Tor is free and community-driven.

Python’s wide range of libraries, particularly the Stem library, makes it easy to interact with Tor’s control interface.

How to Use Python with Tor to Change Your IP Address

To dynamically change your IP address using Python and Tor, you’ll need to follow these steps:

Step 1. Setting Up Tor for Python

1. Install Tor on Your System

First, you need to install the Tor service on your system.

  • On Linux (Ubuntu/Debian):

Install Tor on Linux

For Copy:

sudo apt update
sudo apt install tor

  • On macOS (Using Homebrew):

Install Tor on macOS

For Copy:

brew install tor

  • On Windows:

Download and install Tor from the official Tor Project website.

2. Configure Tor to Accept Control Commands

Edit the Tor configuration file (torrc) to allow Python to communicate with the Tor service.

a. Open the Tor configuration file:

Open the Tor configuration file

For Copy:

sudo nano /etc/tor/torrc

b. Add or uncomment the following lines:

Add or uncomment

For Copy:

ControlPort 9051
HashedControlPassword <hashed-password>

Note: Replace <hashed-password> with a hashed password generated using the tor --hash-password <your-password> command.

c. Restart the Tor service for the changes to take effect:

Restart the Tor service

For Copy:

sudo systemctl restart tor

Step 2. Install Required Python Libraries

You’ll need Python libraries to interact with Tor and send requests. Install them using pip:

1. stem: A Python controller library for interacting with the Tor network.
Install it with:

install stem

For Copy:

pip install stem

2. requests: For making HTTP requests through Tor.
Install it with:

For Copy:

pip install requests

Step 3. Establish a Connection to Tor

The following example demonstrates how to connect to Tor and use it to send HTTP requests.

Establish a Connection to Tor Example

For Copy:

import requests

# Define the Tor proxy
proxies = {
    "http": "socks5h://127.0.0.1:9050",
    "https": "socks5h://127.0.0.1:9050",
}

# Test the connection by checking your IP address
url = "http://httpbin.org/ip"

response = requests.get(url, proxies=proxies)
print(f"Current IP Address: {response.text}")

In this example:

  • socks5h://127.0.0.1:9050 is the default Tor SOCKS proxy address.
  • httpbin.org/ip returns the external IP address of your connection.

Step 4. Change Your Tor IP Address Using stem

To programmatically change your IP address, you’ll need to send a NEWNYM signal to the Tor service. The stem library makes this easy.

Code Example: Rotating Tor IP

Code Example Rotating Tor IP

For Copy:

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

# Function to change the Tor IP address
def change_tor_ip():
    with Controller.from_port(port=9051) as controller:
        controller.authenticate(password="your-password")  # Use the password you configured in torrc
        controller.signal(Signal.NEWNYM)  # Request a new Tor circuit (new IP)
        print("Tor IP address has been changed!")

# Function to make a request through Tor
def get_current_ip():
    proxies = {
        "http": "socks5h://127.0.0.1:9050",
        "https": "socks5h://127.0.0.1:9050",
    }
    url = "http://httpbin.org/ip"
    response = requests.get(url, proxies=proxies)
    return response.text

# Example usage
print("Initial IP:", get_current_ip())
change_tor_ip()
print("New IP:", get_current_ip())

In this example:

  • Signal.NEWNYM instructs Tor to create a new circuit, resulting in a new IP address.
  • Replace "your-password" with the password configured in the torrc file.

Step 5. Automate IP Rotation

If you need to rotate IPs periodically (e.g., for web scraping), you can automate the process with a loop.

Automate IP Rotation with a loop

For Copy:

import time

for i in range(5):  # Rotate IP 5 times
    print(f"IP before rotation: {get_current_ip()}")
    change_tor_ip()
    time.sleep(10)  # Wait 10 seconds for Tor to create a new circuit
    print(f"IP after rotation: {get_current_ip()}")

Tips on Changing IP Addresses with Tor and Python

To prevent any hitches, make sure to follow these steps:

1. Respect website rules

If for web scraping, please respect the terms of service of your target websites.

2. Limit requests

Leave a delay between requests to avoid being flagged, blocked, or slowing down Tor's network.

3. Monitor Tor logs

Check for errors or warnings regularly.

4. Implement error handling

Make sure your script can handle errors. For example, connection timeouts or an IP change that fails.

5. Test your setup

Before deploying, test whether the IP change actually works as you expected.

6. Keep updating your software

Update both Tor Browser and Python libraries for the latest security features and bug fixes.

7. Do not overload Tor

Please note, Tor is a shared network. Use it responsibly and avoid overload.

Troubleshooting Common Issues

Here are some common problems you might encounter and how to fix them:

1. Tor Control Port Connection Error

Ensure the control port (9051) is open and the password is correctly configured in the torrc file.

2. IP Not Changing

Tor might assign you the same IP for exit nodes limited. Wait a few seconds before requesting a new IP.

3. Requests Not Routing Through Tor

Check that your Python script uses the correct proxy settings (socks5h://127.0.0.1:9050).

FAQs About Python Tor Change IP Address

1. Is it legal to use Tor for changing IP addresses?

Yes. However, ensure not using it for illegal activities or violating website terms of service.

2. Can I use Tor for web scraping?

Yes, but be cautious. Some websites actively block Tor traffic, and excessive scraping may lead to IP bans or legal consequences. Combine Tor with CAPTCHA-solving tools and user-agent rotation for better results.

3. How often can I change my Tor IP address?

You can request a new IP address using the NEWNYM signal, but frequent requests may not always result in a new IP due to Tor's limited exit node pool. Adding a delay (e.g., 10 seconds) ensures Tor has time to establish a new circuit.

Conclusion

Using Python and Tor to change your IP address can efficiently enhance your online privacy and anonymity. For easier solutions, you could consider integrating rotating proxies into your workflow. This combination will provide better security and flexibility. Ideal for web scraping and accessing geo-restricted content. 

If you are looking for proxies to improve your work easily, consider reliable providers like MacroProxy. Quality proxies at reasonable prices. You can get a free test chance before payment to check the effectiveness.

< Previous

Next >

Get Started with a Free Trial

Don't wait! Click the button below to start your free trial and see the difference MacroProxy's proxies can make.