Tunneling httplib Through a Proxy
我试图弄清楚如何通过代理将数据发送到服务器。 我希望通过tor可以做到这一点,但由于tor使用SOCKS,因此显然无法使用httplib(如果我错了,请纠正我)
这就是我现在所拥有的
1 2 3 4 | import httplib con = httplib.HTTPConnection("google.com") con.set_tunnel(proxy, port) con.send("Sent Stuff") |
问题是,设置隧道后,它似乎冻结了。 谢谢你的帮助。
如果要使用http代理,则应如下所示:
1 2 3 | import httplib conn = httplib.HTTPConnection(proxyHost, proxyPort) conn.request("POST","http://www.google.com", params) |
如果要使用SOCKS代理,可以使用SocksiPy,如以下问题所示:如何将SOCKS 4/5代理与urllib2一起使用?
看起来正确的答案是:
http://bugs.python.org/issue11448#msg130413
1 2 3 4 | import httplib con = httplib.HTTPConnection(proxyHost, proxyPort) con.set_tunnel("www.google.com", 80) con.send("Sent Stuff") |
作为Khue Vu回答的后续,这是一个完整的示例,将其与SOCKS代理一起使用的细节比预期的要复杂。
首先安装PySocks:
1 | pip install PySocks |
然后,您需要在实例化HTTPConnection并通知其将使用代理的情况下手动设置SOCKS代理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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