Search code examples
pythonpython-3.xpython-requeststorsocks

Make a python 3 request using proxy


I want to make an anonymous web request using python 3.

I've tried few suggestions such as: Make requests using Python over Tor

I've managed to get a fake ip using this snippet:

Installation

pip install requests requests[socks]

Basic usage

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:9150',
                       'https': 'socks5://127.0.0.1:9150'}
    return session

# Make a request through the Tor connection
# IP visible through Tor
session = get_tor_session()
print(session.get("http://httpbin.org/ip").text)
# Above should print an IP different than your public IP

# Following prints your normal public IP
print(requests.get("http://httpbin.org/ip").text)

But that works only on port 9150 and when the tor web browser works. I want to make a request without the tor browser, as i want to Dockerize the whole thing.

I've read about Socks5, and as you can see i've installed it, but when i make a request on port 9050 on the same snippet i get:

requests.exceptions.ConnectionError: SOCKSHTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /ip (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))

How can i solve it?

Thanks!


Solution

  • 10061 is 'connection refused'

    That means there was nothing listening on that port you tried to connect to, no service is up and running (no open port) or firewall on target IP blocks it

    you can test that port with telnet

    telnet `IP` `PORT`
    

    And also check this port issue on Windows: here