How to Use Python and Tor to Rotate IP Addresses Every Minute for Enhanced Anonymity

spyboy's avatarPosted by

Using Tor with Python allows you to rotate your IP address and bounce network traffic through different IPs, adding an extra layer of anonymity to web requests. Coupled with rotating User-Agent headers, this approach can prevent detection by websites, avoid blocks, and improve anonymity when performing web scraping, penetration testing, or any automation tasks that need privacy. Here’s an extensive guide on setting up Python with Tor, rotating IP addresses, and changing User-Agent headers for each request.


Prerequisites

Before getting started, ensure you have the following:

  1. Python installed on your system.
  2. Tor installed and running as a service.
  3. Additional Python libraries: requests, fake_useragent, and stem. Install them using pip:
   pip install requests fake-useragent stem

Step 1: Install and Configure Tor

For Debian-based systems, you can install Tor with the following command:

sudo apt-get install tor

Once installed, start the Tor service:

sudo service tor start

Configure the Tor Service

To allow Python to communicate with the Tor network and change IP addresses on demand, enable the Tor control port. Open the torrc file, typically located in /etc/tor/torrc:

sudo nano /etc/tor/torrc

Uncomment or add the following lines:

ControlPort 9051
CookieAuthentication 1

Save and restart Tor:

sudo service tor restart

Step 2: Python Code to Rotate IP and User-Agent

This code uses requests to make HTTP requests through Tor, stem to communicate with the Tor controller and change IPs, and fake_useragent to randomize User-Agent headers.

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

# Tor proxies setup for HTTP and HTTPS
proxies = {
    'http': 'socks5://127.0.0.1:9050',
    'https': 'socks5://127.0.0.1:9050'
}

print("Changing IP Address every 30 seconds...\n")

while True:
    try:
        # Random User-Agent for each request
        headers = { 'User-Agent': UserAgent().random }

        # Connect to the Tor Controller and switch IP
        with Controller.from_port(port=9051) as controller:
            controller.authenticate()  # Ensure this is configured in torrc
            controller.signal(Signal.NEWNYM)
            print("Requested new IP...")

        # Wait for the Tor network to update the IP
        time.sleep(5)

        # Request the current IP address to verify the change
        response = requests.get('https://ident.me', proxies=proxies, headers=headers)
        print(f"Your IP is: {response.text} || User Agent: {headers['User-Agent']}")

    except requests.RequestException as req_err:
        print(f"Network error: {req_err}")

    except Exception as err:
        print(f"An error occurred: {err}")

    # Wait before switching IP again to avoid overloading Tor network
    time.sleep(30)

Code Breakdown

  • Tor Proxy Setup: We define a proxy dictionary using the Tor SOCKS5 proxy (127.0.0.1:9050).
  • IP Rotation: Each time we connect to the Tor control port (9051), we send a NEWNYM signal to request a new IP address.
  • User-Agent Randomization: The UserAgent().random from fake_useragent library generates a different User-Agent string for each request, making it harder for websites to detect automation.
  • Requesting IP Verification: After changing the IP, we verify it by sending a request to https://ident.me, a service that returns your current public IP address.
  • Loop: The code waits for 30 seconds before requesting a new IP to avoid overloading the Tor network and respect Tor’s fair use policy.

Use Cases for This Setup

  1. Web Scraping and Data Collection
  • By rotating IP addresses and User-Agent headers, you can scrape websites without getting blocked. This setup reduces the likelihood of detection, especially on websites that implement anti-bot measures.
  1. Penetration Testing and Anonymity
  • Ethical hackers and penetration testers use Tor to conceal their IP address while conducting reconnaissance or other activities. Changing IPs and User-Agents frequently can make activities less traceable.
  1. Bypassing Geo-Restrictions
  • Many websites restrict content based on geographic location. By using Tor, you can access content as if you’re browsing from different locations, as Tor routes traffic through nodes around the world.
  1. Avoiding IP Bans in API Testing
  • When testing APIs, especially ones with rate-limits or strict IP restrictions, frequent IP rotation prevents hitting limits or getting banned.
  1. Enhanced Anonymity for Personal Use
  • Everyday internet users who are privacy-conscious can use this setup to hide their IP and User-Agent from websites, protecting against tracking and profiling.

Potential Limitations and Considerations

  1. Speed: Tor can be slow, especially if connecting through many nodes. The process of frequently changing IPs may reduce your request throughput.
  2. Exit Node Reliability: Not all Tor exit nodes work reliably with every website. Some websites may block known Tor exit nodes, which could lead to connectivity issues.
  3. Legal Implications: Always make sure to use this setup within the bounds of the law. Unauthorized scraping or accessing restricted information may lead to legal consequences.
  4. Fair Use Policy for Tor: Tor is a shared network; overloading it with frequent requests affects its performance. Use this setup sparingly and ethically.

Troubleshooting

If you encounter issues, here are a few troubleshooting tips:

  • Authentication Issues: Make sure you have configured CookieAuthentication in your torrc file. If you still have trouble, try setting a password for Tor authentication.
  • User-Agent Not Changing: If your User-Agent isn’t changing, try reinstalling the fake-useragent library or updating it to the latest version.
  • Tor Connectivity: If you’re unable to connect to Tor, verify that Tor is running (sudo service tor status). Restart the service if needed.

Conclusion

Using Python with Tor to rotate IPs and User-Agent headers can be a powerful tool for anonymity and avoiding detection. Whether you’re scraping data, conducting penetration tests, or simply browsing with enhanced privacy, this setup provides flexibility, security, and ease of use. Always use such tools responsibly and respect the fair use of shared resources like Tor.

One comment

Leave a reply to Xavier Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.