How to pass all Python's traffics through a http proxy?

habedi picture habedi · Jul 26, 2015 · Viewed 59.6k times · Source

I want to pass all Python's traffics through a http proxy server, I checked urlib2 and requests packages for instance, they can be configured to use proxies but how could I use something like a system-wide proxy for Python to proxy all the data out?

Answer

efirvida picture efirvida · Jul 26, 2015

Linux system first export the environment variables like this

$ export http_proxy="http://<user>:<pass>@<proxy>:<port>"
$ export HTTP_PROXY="http://<user>:<pass>@<proxy>:<port>"

$ export https_proxy="http://<user>:<pass>@<proxy>:<port>"
$ export HTTPS_PROXY="http://<user>:<pass>@<proxy>:<port>"

or in the script that you want to pass through the proxy

import os

proxy = 'http://<user>:<pass>@<proxy>:<port>'

os.environ['http_proxy'] = proxy 
os.environ['HTTP_PROXY'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTPS_PROXY'] = proxy

#your code goes here.............

then run python script

$ python my_script.py

UPDATE

An also you can use redsocks with this tool you can redirect silently all your TCP connections to a PROXY with or without authentication. But you have to take care because it's for all connections not only for the python.

Windows systems you can use tools like freecap, proxifier, proxycap, and configure to run behind the python executable