Skip to content

Instantly share code, notes, and snippets.

@kristovatlas
Created June 7, 2017 19:23
Show Gist options
  • Save kristovatlas/d8e9bc41fbf1d3cfec3fa69747992c87 to your computer and use it in GitHub Desktop.
Save kristovatlas/d8e9bc41fbf1d3cfec3fa69747992c87 to your computer and use it in GitHub Desktop.
Demo requests using Tor and changing circuits
"""Prints external IP address and a few bytes from example.com repeatedly."""
import time
from torrequests import Tor # pip install torrequests
from stem import Signal # pip install stem
from stem.control import Controller # pip install stem
SLEEP_SEC_BT_REQS = 10
def _new_nym():
"""
You must configure your torrc file to designate a Control Port before
connecting in this fashion. For example, if using Tor Browser on MacOS:
Add this line:
ControlPort 9151
To this file:
~/Library/Application Support/TorBrowser-Data/Tor/torrc
"Tor does not have a method for cycling your IP address. This is on purpose,
and done for a couple reasons. The first is that this capability is usually
requested for not-so-nice reasons such as ban evasion or SEO. Second,
repeated circuit creation puts a very high load on the Tor network, so
please don't!"
https://stem.torproject.org/faq.html#how-do-i-request-a-new-identity-from-tor
"""
with Controller.from_port(port=9151) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)
def _main():
tor = Tor(tor_ip='127.0.0.1', tor_port=9150)
for _ in range(0, 3):
print tor.getPublicIP()
req = tor.get('http://example.com/')
print req.text[0:30]
_new_nym()
time.sleep(SLEEP_SEC_BT_REQS)
if __name__ == '__main__':
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment