The pysocks module is a Python module that provides a simple and consistent interface to work with SOCKS proxies. SOCKS is a protocol that facilitates the routing of network packets between a client and server through a proxy server. This module allows you to use SOCKS proxies with various Python libraries, including urllib, httplib, and requests.
The pysocks module to make a request through a SOCKS proxy:
Install pysocks:
pip3 install pysocks
pip3 install requestsUsing Tor with Python Requests
This Python script demonstrates how to use the Requests library to make HTTP requests through the Tor network. It sets up a Tor session and sends requests through Tor, allowing you to access websites with increased anonymity.
Function: get_tor_session()
def get_tor_session():
session = requests.session()
# Tor uses the 9050 port as the default socks port
session.proxies = {'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050'}
return sessionThis function creates a new Requests session and configures it to use the Tor network. It sets the session’s proxies to use the Tor SOCKS5 proxy at 127.0.0.1:9050.
Print Normal Public IP:
print("Normal Public IP:", requests.get("http://httpbin.org/ip").text)This line makes a regular HTTP request to http://httpbin.org/ip to get the public IP address without using Tor. It serves as a baseline for comparison.
Print IP for Tor Connection:
# Make a request through the Tor connection
# IP visible through Tor
session = get_tor_session()
print("IP for Tor connection:", session.get("http://httpbin.org/ip").text)
# Above should print an IP different than your public IPHere, a request is made through the Tor connection, and the resulting IP address is printed. This IP should be different from the public IP obtained in the previous step, demonstrating that the request is being routed through the Tor network.
Accessing .onion Website:
response = session.get('https://duckduckgogg42xjoc72x3sjasowoarfbgcmvfimaftt6twagswzczad.onion/')This line sends a GET request to the Duck Duck Go onion service, which is accessible only through the Tor network. It demonstrates how to access .onion websites using the Tor-configured session.
Print Headers:
#get headers dictionary response
for key, value in response.headers.items():
print(key, value)This loop prints the headers of the response from the .onion website. Headers may contain information about the server, content type, and other details.
import requests
def get_tor_session():
session = requests.session()
# Tor uses the 9050 port as the default socks port
session.proxies = {'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050'}
return session
# Following prints your normal public IP
print("Normal Public IP:",requests.get("http://httpbin.org/ip").text)
# Make a request through the Tor connection
# IP visible through Tor
session = get_tor_session()
print("IP for Tor connection:",session.get("http://httpbin.org/ip").text)
# Above should print an IP different than your public IP
response = session.get('https://duckduckgogg42xjoc72x3sjasowoarfbgcmvfimaftt6twagswzczad.onion/')
#get headers dictionary response
for key,value in response.headers.items():
print(key,value)This script illustrates how to use Tor with Python’s Requests library to enhance anonymity while making HTTP requests. Make sure you have Tor running on your local machine (127.0.0.1:9050) for this script to work properly.
Using Tor with torrequest Library
This Python script demonstrates how to use the torrequest library, a wrapper around the requests library, to interact with the Tor network. It allows you to send HTTP requests through Tor, enhancing privacy and anonymity.
Setting Up TorRequest:
from torrequest import TorRequest
# Establish a TorRequest session
with TorRequest(proxy_port=9050, ctrl_port=9051, password=None) as tr:This code snippet creates a TorRequest session. The proxy_port and ctrl_port parameters specify the Tor SOCKS5 proxy and the Tor control port, respectively.
Sending a Request and Printing IP:
response = tr.get('http://ipecho.net/plain')
print(response.text) # not your IP addressHere, a GET request is made to http://ipecho.net/plain to obtain the current public IP address through Tor. The response is then printed, demonstrating that the request is routed through the Tor network.
Accessing Underlying Stem Controller and Resetting Identity:
# TorRequest object also exposes the underlying Stem controller
# and Requests session objects for more flexibility.
print(type(tr.ctrl)) # a stem.control.Controller object
# Reset the Tor identity
tr.reset_identity()This part of the code showcases additional functionalities. It prints the type of the underlying Stem controller object (tr.ctrl) and resets the Tor identity. Resetting the identity means establishing a new circuit in the Tor network, effectively changing the IP address.
Sending Another Request After Identity Reset:
response = tr.get('http://ipecho.net/plain')
print(response.text) # another IP addressAfter resetting the Tor identity, a new GET request is made to http://ipecho.net/plain, and the response is printed. This IP address should differ from the one obtained in the previous request, showcasing the change in identity.
from torrequest import TorRequest
with TorRequest(proxy_port=9050, ctrl_port=9051, password=None) as tr:
response = tr.get('http://ipecho.net/plain')
print(response.text) # not your IP address
# TorRequest object also exposes the underlying Stem controller
# and Requests session objects for more flexibility.
print(type(tr.ctrl)) # a stem.control.Controller object
tr.ctrl.signal('CLEARDNSCACHE') # see Stem docs for the full AP
tr.reset_identity()
response = tr.get('http://ipecho.net/plain')
print(response.text) # another IP addressExplanation Summary:
- The script demonstrates how to use the
torrequestlibrary to send requests through the Tor network. - It showcases the ability to reset the Tor identity, providing a new IP address for enhanced anonymity.
- The
TorRequestobject exposes the underlying Stem controller, allowing for additional flexibility and control over Tor-related functionalities.
Ensure that you have Tor running on your local machine (127.0.0.1:9050 and 127.0.0.1:9051) for this script to work correctly.
Using Tor with torpy Library
pip3 install torpyThis Python script demonstrates how to use the torpy library to send HTTP requests through the Tor network. The torpy library provides a simple interface for working with Tor in Python.
Setting Up Tor Connection:
from torpy.http.requests import TorRequests
# Establish a TorRequests session
with TorRequests() as tor_requests:This code initializes a TorRequests session, creating a connection to the Tor network.
Building and Renewing Circuits:
print("building circuit...")
with tor_requests.get_session() as session:
print(session.get("http://httpbin.org/ip").json())
print("renewing circuit...")
with tor_requests.get_session() as session:
print(session.get("http://httpbin.org/ip").json())Here, the script builds a Tor circuit, makes a request to http://httpbin.org/ip, prints the obtained IP address, and then renews the circuit to obtain a new IP address. This demonstrates the ability to manage circuits for enhanced anonymity.
Accessing .onion Website:
response = session.get('http://3g2upl4pq6kufc4m.onion')
for key, value in response.headers.items():
print(key, value)This part of the code sends a request to the DuckDuckGo onion service (.onion domain) and prints the headers of the response. Accessing a .onion website showcases the ability to interact with Tor hidden services.
from torpy.http.requests import TorRequests
with TorRequests() as tor_requests:
print("building circuit...")
with tor_requests.get_session() as session:
print(session.get("http://httpbin.org/ip").json())
print("renewing circuit...")
with tor_requests.get_session() as session:
print(session.get("http://httpbin.org/ip").json())
response = session.get('http://3g2upl4pq6kufc4m.onion')
for key,value in response.headers.items():
print(key,value)Explanation Summary:
- The script uses the
torpylibrary to establish a connection to the Tor network and manage Tor circuits. - It demonstrates the process of building a circuit, making requests, and renewing the circuit to obtain a new IP address.
- Accessing a .onion website is showcased, highlighting the ability to interact with Tor hidden services.
Ensure that you have Tor running on your local machine for this script to work correctly. The torpy library simplifies Tor integration in Python, making it easier to work with Tor circuits and hidden services.
Custom Proxy Configuration in Python
This Python script demonstrates how to enable and disable a SOCKS proxy for network connections by temporarily modifying the behavior of the socket module.
**1. *Disable Proxy Function:*
temp_socket = socket.socket
temp_create_connection = socket.create_connection
def disable_proxy():
socket.socket = temp_socket
socket.create_connection = temp_create_connectionThe disable_proxy function saves the original socket.socket and socket.create_connection functions and then restores them. This effectively disables the use of a proxy.
**2. *Enable Proxy Function:*
def enable_proxy(host="127.0.0.1", port=9050):
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, host, port, True)
socket.socket = socks.socksocket
socket.create_connection = create_connectionThe enable_proxy function configures the socket module to use a SOCKS5 proxy. It sets the default proxy type and address using the socks library. Additionally, it replaces the original socket.socket and socket.create_connection functions with custom versions that utilize the SOCKS proxy.
Explanation Summary:
- The script provides two functions:
enable_proxyanddisable_proxy. enable_proxysets up a SOCKS5 proxy configuration forsocketby using thesockslibrary. It overrides thesocket.socketandsocket.create_connectionfunctions to enable the proxy.disable_proxyrestores the originalsocketfunctions, effectively disabling the proxy configuration.
import socks
import socket
temp_socket = socket.socket
temp_create_connection = socket.create_connection
def disable_proxy():
socket.socket = temp_socket
socket.create_connection = temp_create_connection
def enable_proxy(host="127.0.0.1", port=9050):
def create_connection(address, timeout=None, source_address=None):
sock = socks.socksocket()
sock.connect(address)
return sock
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, host, port, True)
socket.socket = socks.socksocket
socket.create_connection = create_connectionUsage:
To use this script, you can call enable_proxy with the desired proxy host and port. After making network connections through the proxy, you can call disable_proxy to revert to the default network configuration.
Note:
Ensure that the socks library is installed (pip install PySocks) before using this script. Also, keep in mind that manipulating the socket module globally may affect the behavior of other parts of your code, so use it judiciously.
Testing Requests with Proxy Configuration
This Python script demonstrates how to use the anonymize library to enable and disable a proxy for HTTP requests using the requests library.
1. Import Libraries and Define Test URL:
import requests
from anonymize import enable_proxy, disable_proxy
# This URL returns your IP as plain text
url = 'http://icanhazip.com'The script imports the necessary libraries (requests, enable_proxy, and disable_proxy) and defines a test URL (http://icanhazip.com) that returns the public IP address.
2. Enable and Test Requests with Proxy:
def test_requests():
print('requests: %s' % requests.get(url).text)
enable_proxy()
test_requests()The test_requests function sends an HTTP GET request to the specified URL and prints the response text. Before calling this function, the enable_proxy function is invoked, which configures the requests library to use a proxy.
3. Disable and Test Requests without Proxy:
disable_proxy()
test_requests()After testing requests with the proxy enabled, the script calls disable_proxy to revert to the default network configuration. Subsequently, it calls test_requests again to demonstrate making requests without the proxy.
import requests
from anonymize import enable_proxy, disable_proxy
#This url returns your ip as plain text
url = 'http://icanhazip.com'
def test_requests():
print('requests: %s' % requests.get(url).text)
enable_proxy()
test_requests()
disable_proxy()
test_requests()Explanation Summary:
- The script utilizes the
anonymizelibrary to enable and disable a proxy for HTTP requests. - The
test_requestsfunction uses therequestslibrary to make an HTTP GET request to a URL that returns the public IP address. - The script first enables the proxy using
enable_proxyand tests requests, then disables the proxy usingdisable_proxyand tests requests again without the proxy.
Note:
Ensure that the anonymize library is properly installed (pip install anonymize) before running this script. Additionally, the effectiveness of the proxy may vary depending on your network setup and the availability of the proxy server.
