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.219.237.229

9 comments

    1. Hello,

      Once you setup your urllib object’s proxy settings you shouldn’t have issues hitting .onions:

      In [1]: r = urllib2.urlopen('http://allyour4nert7pkh.onion')
      
      In [2]: r.getcode()
      Out[2]: 200
      
      In [3]: r.url
      Out[3]: 'http://allyour4nert7pkh.onion'
      
      In [4]: r.headers.values()
      Out[4]:
      ['86',
       'bytes',
       'nginx/1.7.2',
       'Fri, 03 Oct 2014 16:09:38 GMT',
       'close',
       '"542eca42-56"',
       'Tue, 18 Nov 2014 16:15:09 GMT',
       'text/html']
      
      1. Not works with .onion

        my code:

        import urllib2

        proxy = urllib2.ProxyHandler({‘http’: ‘127.0.0.1:8118’})

        opener = urllib2.build_opener(proxy)

        urllib2.install_opener(opener)

        response = urllib2.urlopen(“http://allyour4nert7pkh.onion”)
        html = response.read()

        print html

        Response:

        urllib2.HTTPError: HTTP Error 404: No such domain

Leave a Reply

Your email address will not be published. Required fields are marked *