如何使 python 请求通过 SOCKS 代理工作
- 2025-03-13 09:09:00
- admin 原创
- 38
问题描述:
我在我的 Python 脚本中使用了很棒的Requests库:
import requests
r = requests.get("http://example.com")
print(r.text)
我想使用 SOCKS 代理,我该怎么做?Requests 似乎只支持 HTTP 代理。
解决方案 1:
现代方式:
pip install -U 'requests[socks]'
然后
import requests
resp = requests.get('http://go.to',
proxies=dict(http='socks5://user:pass@host:port',
https='socks5://user:pass@host:port'))
解决方案 2:
如果有人尝试了所有这些较旧的答案,但仍然遇到以下问题:
requests.exceptions.ConnectionError:
SOCKSHTTPConnectionPool(host='myhost', port=80):
Max retries exceeded with url: /my/path
(Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSConnection object at 0x106812bd0>:
Failed to establish a new connection:
[Errno 8] nodename nor servname provided, or not known',))
这可能是因为默认情况下配置为在连接的本地requests
端解析 DNS 查询。
尝试将代理 URL 从socks5://proxyhost:1234
更改为socks5h://proxyhost:1234
。请注意 extra h
(它代表主机名解析)。
PySocks 包模块默认执行远程解析,我不确定为什么它们的集成会有如此明显的差异,但正如一些评论者指出的那样,curl 就是这样工作的。
解决方案 3:
从2016-04-29 发布的2.10.0requests
版本开始支持 SOCKS。requests
它需要PySocks,可以通过 来安装pip install pysocks
。
使用示例:
import requests
proxies = {'http': "socks5://myproxy:9191"}
requests.get('http://example.org', proxies=proxies)
解决方案 4:
您需要安装pysocks,我的版本是 1.0 并且代码对我有用:
import socket
import socks
import requests
ip='localhost' # change your proxy's ip
port = 0000 # change your proxy's port
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)
socket.socket = socks.socksocket
url = u'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=inurl%E8%A2%8B'
print(requests.get(url).text)
解决方案 5:
https_proxy
您可以使用环境变量运行脚本。
如果有必要的话,安装袜子支撑。
pip install PySocks
设置环境变量
export https_proxy=socks5://<hostname or ip>:<port>
运行脚本。此示例使用代理发出请求并显示 IP 地址:
echo Your real IP
python -c 'import requests;print(requests.get("http://ipinfo.io/ip").text)'
echo IP with socks-proxy
python -c 'import requests;print(requests.get("https://ipinfo.io/ip").text)'
解决方案 6:
一旦 pythonrequests
与 pull request 合并,SOCKS5
它就会像使用proxies
字典一样简单:
更新:PR 已经合并。
#proxy
# SOCKS5 proxy for HTTP/HTTPS
proxies = {
'http' : "socks5://myproxy:9191",
'https' : "socks5://myproxy:9191"
}
#headers
headers = {
}
url='http://example.com/'
res = requests.get(url, headers=headers, proxies=proxies)
查看SOCKS 代理支持
另一个选择是,如果您不能等到request
准备好,当您无法使用时requesocks
- 就像在 GoogleAppEngine 上由于缺少pwd
内置模块一样,使用上面提到的PySocks :
socks.py
从 repo 中获取文件并将副本放在你的根文件夹中;添加
import socks
和import socket
此时,在使用 with 之前配置并绑定套接字,urllib2
如下例所示:
import urllib2
import socket
import socks
socks.set_default_proxy(socks.SOCKS5, "myprivateproxy.example",port=9050)
socket.socket = socks.socksocket
res=urllib2.urlopen(url).read()
解决方案 7:
# SOCKS5 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks5://1.2.3.4:1080",
'https' : "socks5://1.2.3.4:1080"
}
# SOCKS4 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks4://1.2.3.4:1080",
'https' : "socks4://1.2.3.4:1080"
}
# HTTP proxy for HTTP/HTTPS
proxiesDict = {
'http' : "1.2.3.4:1080",
'https' : "1.2.3.4:1080"
}
解决方案 8:
我可以在 Linux 上做到这一点。
$ pip3 install --user 'requests[socks]'
$ https_proxy=socks5://<hostname or ip>:<port> python3 -c \n> 'import requests;print(requests.get("https://httpbin.org/ip").text)'
解决方案 9:
我在 urllib3 中安装了 pysocks 和 monkey patched create_connection,如下所示:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 1080)
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, socket_options=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
if host.startswith('['):
host = host.strip('[]')
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socks.socksocket(af, socktype, proto)
# If provided, set socket level options before connecting.
# This is the only addition urllib3 makes to this function.
urllib3.util.connection._set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as e:
err = e
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list")
# monkeypatch
urllib3.util.connection.create_connection = create_connection