Friday, May 1, 2015

How To Change TOR Browser IP or Identity using Python

Tor is a good and huge organization which stand alone with contribution from all over the world. Their aim is to satisfy anonymity need of people for free. They have option for donation, even you can just donate a server, and they run tor exit nodes on it. That's how they are still around.

When it comes to scraping, anonymity may not be your first task to accomplish. You have to satisfy other stuff before that, like avoiding anti-scrape measures. Most famous one is ip-bans, and it may become annoying and unsolvable without using proxies.

Many company offers proxies on the internet, havent bought one and probably will never. That's because of Tor, and happy to use it.

In many scenarious when you banned and can't access to site no more, then you have to change identity and move on. Normallt this requires manual script run or clicking on browser. If we are building non-stop fully automatic bots, then we have to find out how to change ip automatic as well.

Our sample here is written in python.

from stem import Signal
from stem.control import Controller

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

If we take a closer look, it connects to port of Tor console. Which is 9051 in this case, but it can be 9151 in some cases. Even you can change these settings in config files. Then we send Authenticate keyword to shake hands. After that we just send our command, NEWNYM which refers to new identity.If status is not "250" then it means you have an error, and attempt was not succesful.

To be able to use stem, you have to install it by pip install stem.

I hope this helps.

Mehmet

1 comment:

  1. Hi Mehmet...I have been trying doing this...but it always gives me stem.socketerror-connection:refused error...can you please tell what should be the settings for torrc file...and what should be its path. Currently I have it in /etc/tor/torrc.
    Thanks in advance!!

    ReplyDelete