通过TOR连接会引发错误

时间:2015-06-28 14:27:01

标签: python tor httplib

我无法通过TOR连接到互联网。我已按照this youtube视频中的所有说明操作,但我仍然收到错误:

Connected to Tor # printed string

Traceback (most recent call last):
  ....
  ....

  File "C:\Python27\lib\httplib.py", line 787, in connect
    self.timeout, self.source_address)
  File "C:\Python27\lib\socket.py", line 571, in create_connection
    raise err
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it  

我附上代码:

import httplib
import socket
import socks

port = 9050
url = 'my-ip.heroku.com'

def connectTor():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", port, True)
    socket.socket = socks.socksocket

def main():
    connectTor()

    print("Connected to Tor")
    conn = httplib.HTTPConnection(url)
    conn.request("GET", "/")
    response = conn.getresponse()
    print(response.read())

if __name__ == "__main__":
    main()

我很困惑因为据说我必须从这个页面下载TOR:https://www.torproject.org/ - 当我安装它时,它工作 - 我可以启动TOR浏览器并浏览。但是这个家伙有一个我没有的Vidalia控制面板。

哪里可能是问题?

1 个答案:

答案 0 :(得分:0)

您应该使用requesocks库通过本地运行的SOCKS代理来路由HTTP请求,而不是直接使用套接字。

从那里,配置您的Session对象以使用本地代理进行http(s),然后发出任意请求:

session = requests.session()
session.proxies = {'http': 'socks5://127.0.0.1:9050',
                   'https': 'socks5://127.0.0.1:9050'}
resp = session.get('https://api.github.com', auth=('user', 'pass'))
print(resp.status_code)
print(resp.text)