Tuesday, September 7, 2010

Working With ToR In Python

I bet I'm not the first one who ever needed to write a script that downloads something via ToR.
Apparently, there isn't much information regarding how to request a new identity or how to use the ToR proxy in Python. So here's a gift from me to the world.

First, while not necessary, I always use a new ToR identity prior to download something through the ToR network. The code looks like:

import socket
def renewTorIdentity():
success = False
s = socket.socket()
s.connect(('localhost', 9051))
resp = s.recv(1024)
if resp.startswith('250'):
s.send("signal NEWNYM\r\n")
resp2 = s.recv(1024)
if resp.startswith('250'):
success = True
return success

That would work assuming "authentication" is set to none in the Vidalia control panel.
After having a new identity, downloading a file is really simple, as Vidalia comes bundled with privoxy configured on port 8118. Here's a sample code for downloading something:

import urllib2
url = "http://something-to-download"
proxy_support = urllib2.ProxyHandler({"http" : ""})
opener = urllib2.build_opener(proxy_support)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open(url).read()
That's it. Simple.


  1. Hi, do you mean resp2 in the second if statement?
    Thank you

  2. Hi! I can't seem to get the download working. I guess the "Bandwidth Graph" should show something when downloading occurs, right?

  3. This works perfectly, and I can use it no problem. But I'm really interested in knowing why it works, could you point me in some way to read more on the topic and actually understand what I'm using?
    Thanks for the code!