Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Tor identity in Python?

Tags:

python

tor

I have the following script:

import socks import socket socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050) socket.socket = socks.socksocket import urllib2  print(urllib2.urlopen("http://www.ifconfig.me/ip").read()) 

which uses tor and SocksiPy

Now I want to change tor identity with each request, for example:

for i in range(0, 10):    #somehow change tor identity    print(urllib2.urlopen("http://www.ifconfig.me/ip").read()) 

How can I do this?

like image 510
user873286 Avatar asked Mar 27 '12 10:03

user873286


People also ask

How do I change my IP with Tor?

It's at the top-right corner of Tor. Click New Identity. Choose this option if you want a new IP address everywhere on Tor and don't want your previous activity to be linked to the new IP address. A pop-up window will appear, warning you that Tor will close all windows and tabs.


2 Answers

Tor wrote a new TOR control library in Python, stem. It can be found on PyPI. They provide some nice tutorials how to work with it, one of them explains how to change your identity:

from stem import Signal from stem.control import Controller  with Controller.from_port(port = 9051) as controller:   controller.authenticate()   controller.signal(Signal.NEWNYM) 

Make sure your config is correct.

like image 92
OrangeTux Avatar answered Sep 23 '22 19:09

OrangeTux


Today, I have searched a lot about this question, and finally managed to answer myself. But before I need to say that pirvoxy and tor should be configured correctly. First script, then a little bit about configuration:

import urllib2 from TorCtl import TorCtl  proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"}) opener = urllib2.build_opener(proxy_support)   def newId():     conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="your_password")     conn.send_signal("NEWNYM")  for i in range(0, 10):     print "case "+str(i+1)     newId()     proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})     urllib2.install_opener(opener)     print(urllib2.urlopen("http://www.ifconfig.me/ip").read()) 

Above script gets new IP and checks it from ifconfig.me web site. About configuration: We need Privoxy. to use TOR with HTTP connections, privoxy should work with tor. We can do it by adding thi to /etc/privoxy/config file:

forward-socks5 / localhost:9050 . #dot is important at the end 

then we configure ControlPort in /etc/tor/torrc file. We need just uncomment this line:

ControlPort 9051 ## If you enable the controlport, be sure to enable one of these ## authentication methods, to prevent attackers from accessing it. HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4C 

then we just restart tor:

/etc/init.d/tor restart 
like image 40
user873286 Avatar answered Sep 21 '22 19:09

user873286