如何通过http代理传递所有Python的流量?

hab*_*edi 17 python proxy reverse-proxy python-2.7

我想通过一个http代理服务器传递所有Python的流量,我检查了urlib2并请求包,例如,它们可以配置为使用代理但是我如何使用类似于Python的系统范围代理来代理所有数据?

efi*_*ida 28

Linux系统首先导出这样的环境变量

$ 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>"
Run Code Online (Sandbox Code Playgroud)

或者在您希望通过代理传递的脚本中

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.............
Run Code Online (Sandbox Code Playgroud)

然后运行python脚本

$ python my_script.py
Run Code Online (Sandbox Code Playgroud)

UPDATE

您还可以使用此工具使用redsocks,您可以使用或不使用身份验证将所有TCP连接静默地重定向到PROXY.但你必须小心,因为它不仅适用于python的所有连接.

Windows系统可以使用freecap,proxifier,proxycap和configure 等工具在python可执行文件后面运行

  • 要使用 SOCKS 协议,请将“http”或“https”替换为“socks4”或“socks5”,如“socks4://127.0.0.1:8080”中所示。 (2认同)

chi*_*ete 5

诚然,这并不是您要寻找的内容,但是如果您知道 Python 代码中所有网络流量的程序化来源,您可以在代码本身中执行此代理包装。建议使用PySocks以下链接中的模块使用纯 python 解决方案:

https://github.com/httplib2/httplib2/issues/22

import httplib2
# detect presense of proxy and use env varibles if they exist
pi = httplib2.proxy_info_from_environment()
if pi:
    import socks
    socks.setdefaultproxy(pi.proxy_type, pi.proxy_host, pi.proxy_port)
    socks.wrapmodule(httplib2)    

# now all calls through httplib2 should use the proxy settings
httplib2.Http()
Run Code Online (Sandbox Code Playgroud)

现在,每次使用 using 进行的调用都httplib2将使用这些代理设置。您应该能够包装任何使用套接字使用此代理的网络模块。

https://github.com/Anorov/PySocks

他们在那里提到不推荐这样做,但它似乎对我来说工作正常。