Using Python urllib2 via Tor

If socks is not installed:

sudo easy_install SocksiPy-branch

Then the following code to check the new IP:

import socks
import socket
def create_connection(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)

socket.socket = socks.socksocket
socket.create_connection = create_connection

import urllib2

try:
    # Check IP
    print urllib2.urlopen("http://almien.co.uk/m/tools/net/ip/").read()
    # Change and check user-agent which is normally Python-Urllib2
    req = urllib2.Request("http://whatismyuseragent.dotdoh.com/")
    req.add_header('User-agent', 'Mozilla 5.10')
    res = urllib2.urlopen(req)
    print res.read()
except urllib2.HTTPError, e:
    print e.code
except urllib2.URLError, e:
    print e.args
Advertisements
Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: