How to Make Urllib2 Requests Through Tor in Python

Make requests using Python over Tor

Here is the code you want to use (download the stem package using pip install stem)

from stem import Signal
from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
controller.authenticate(password='your password set for tor controller port in torrc')
print("Success!")
controller.signal(Signal.NEWNYM)
print("New Tor connection processed")

Good luck and hopefully that works.

Urllib2 using Tor and socks in python

To get ip from specific country you have to set two parameters ExitNodes={countrycode} and StrictNodes=1.Here for India country code is {in}.To know country code check http://www.b3rn3d.com/blog/2014/03/05/tor-country-codes/.
Using python you can set the these parameters as follows

Code:-

import socks
import socket
import urllib2

def newIdentity(self):
socks.setdefaultproxy()
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("127.0.0.1", 9051))
s.send('AUTHENTICATE "my_password" \r\n')
response = s.recv(128)
if response.startswith("250"):
s.send("SETCONF ExitNodes={in}\r\n")
s.send("SETCONF StrictNodes=1\r\n")
s.send("SIGNAL NEWNYM\r\n")
s.close()
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
if __name__ == '__main__':
newIdentity()
print urllib2.urlopen('http://my-ip.herokuapp.com').read()

how to access a website with python through tor, successfully? ports 8118 and 9050 don't work?

TOR provides a SOCKS proxy. Since urllib2 can only handle HTTP proxies, you'll have to use a SOCKS implementation.

Tor doesn't work with urllib2

Maybe this answer is related.

In a nutshell, you're using 127.0.0.1:8118 as a proxy url, and http as your protocol, but the protocol should be https instead.



Related Topics



Leave a reply



Submit