Python 使用代理

参考: https://blog.denghaihui.com/2017/10/10/shadowsocks-polipo/

命令行shadowsocks

安装

sudo apt install shadowsocks

使用

Proxy options:
  -c CONFIG              path to config file
  -s SERVER_ADDR         server address
  -p SERVER_PORT         server port, default: 8388
  -b LOCAL_ADDR          local binding address, default: 127.0.0.1
  -l LOCAL_PORT          local port, default: 1080
  -k PASSWORD            password
  -m METHOD              encryption method, default: aes-256-cfb
  -t TIMEOUT             timeout in seconds, default: 300
  -a ONE_TIME_AUTH       one time auth
  --fast-open            use TCP_FASTOPEN, requires Linux 3.7+

http协议转换 polipo

安装

sudo apt install polipo

配置

sudo vim /etc/polipo/config
# This file only needs to list configuration variables that deviate
# from the default values.  See /usr/share/doc/polipo/examples/config.sample
# and "polipo -v" for variables you can tweak and further information.
logSyslog = true
logFile = /var/log/polipo/polipo.log
proxyAddress = "0.0.0.0"
proxyPort = 8123
socksParentProxy = "127.0.0.1:1080"
socksProxyType = socks5
allowedClients = 127.0.0.1

重启polipo

sudo /etc/init.d/polipo restart

设置shell的 http/https代理

针对当前shell有效

export http_proxy="http://127.0.0.1:8123" && export https_proxy="http://127.0.0.1:8123"

curl ip.gs   // 测试

针对单条命令

http_proxy=http://localhost:8123 curl ip.gs

python 脚本代理

python的脚本使用代理时, 实验发现以上针对shell和单条命令的方案都无法生效, 依旧需要在python内部制定代理,python有几种库可以指定代理

Python库: urllib

# 8123端口用于polipo转换http协议到socket5协议, 1080: 是支持shadowsocket的socket5协议
proxy_support = urllib.request.ProxyHandler({'socket5': '127.0.0.1:1080', 'http': '127.0.0.1:8123', 'https': '127.0.0.1:8123'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)

f = urllib.request.urlopen("http://twitter.com/%s/status/%s" % (uid, sid))
html = str(f.read(), "utf-8")
原文地址:https://www.cnblogs.com/JohnRain/p/10550581.html