Using Tor With Python

Using tor with python’s urllib2 is pretty easy, you just need to setup a few things before hand.

First off what is tor? Tor stands for " The Onion Router " and allows you to anonymously browse the internet by bouncing your request through multiple tor nodes.

htw2

I’m going to be using a Fedora 17 machine to demonstrate, and show output.

First lets install two packages from our package manager:

# yum install privoxy tor

Next we need to edit our privoxy config ( /etc/privoxy/config ) and add the following line:

forward-socks4a / localhost:9050 .

We are now set to start the services:

service tor start
service privoxy start

Lets go ahead and fire up our Python interrupter and get to it:

In [1]: import urllib2

In [2]: proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8118'})

In [3]: opener = urllib2.build_opener(proxy)

In [4]: urllib2.install_opener(opener)

In [5]: print urllib2.urlopen('http://icanhazip.com/').read()
78.108.63.46

To verify we are working we can request a new identity from the

tor process by sending the SIGHUP signal:

# ps aux | grep tor
root      5126  0.5  0.9  61752 19068 pts/1    S+   15:24   0:00 tor
root      5289  0.0  0.0 109400   824 pts/3    R+   15:26   0:00 grep --color=auto tor

# kill -s SIGHUP 5126

Now when we run our Python code we should have a new ip address:

In [6]: print urllib2.urlopen('http://icanhazip.com/').read()
91.213.137.129