通过代理隧道httplib

时间:2012-08-04 03:52:35

标签: python sockets proxy tunnel httplib

我试图弄清楚如何通过代理将数据发送到服务器。我希望通过tor可以实现这一点,但是当使用SOCKS时,显然用httplib是不可能的(如果我错了,请纠正我)

这就是我现在所拥有的

import httplib
con = httplib.HTTPConnection("google.com")
con.set_tunnel(proxy, port)
con.send("Sent Stuff")

问题是,隧道设置时似乎冻结了。谢谢你的帮助。

3 个答案:

答案 0 :(得分:16)

如果你想使用http代理,它应该是这样的:

import httplib
conn = httplib.HTTPConnection(proxyHost, proxyPort)
conn.request("POST", "http://www.google.com", params)

如果您想使用SOCKS代理,可以像以下问题一样使用SocksiPy:How can I use a SOCKS 4/5 proxy with urllib2?

答案 1 :(得分:6)

看起来正确的答案是:

http://bugs.python.org/issue11448#msg130413

import httplib
con = httplib.HTTPConnection(proxyHost, proxyPort)
con.set_tunnel("www.google.com", 80)
con.send("Sent Stuff")

答案 2 :(得分:1)

作为Khue Vu回答的后续内容,这里有一个完整的例子,使用SOCKS代理进行此操作的详细信息比预期的要复杂得多。

首先安装PySocks:

pip install PySocks

然后,您需要在实例化HTTPConnection并通知它将使用代理后手动设置SOCKS代理:

from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

import socks

url = urlparse("http://final.destination.example.com:8888/")

conn = HTTPConnection('127.0.0.1', 9000) # use socks proxy address
conn.set_tunnel(url.netloc, url.port) # remote host and port that you actually want to talk to
conn.sock = socks.socksocket() # manually set socket
conn.sock.set_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9000) # use socks proxy address
conn.sock.connect((url.netloc, url.port)) # remote host and port that you actually want to talk to

request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)

请注意,上面的导入是python3.x