Last active
August 29, 2015 14:18
-
-
Save zlhaa23/07c193dfd44481702f01 to your computer and use it in GitHub Desktop.
Use Tor to send HTTP requests from multiple IP addresses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stem.torproject.org/tutorials/to_russia_with_love.html#using-socksipy | |
# http://segmentfault.com/q/1010000000511783/a-1020000000512182 | |
# https://github.com/kennethreitz/requests/pull/478#issuecomment-24914571 | |
# Python 3 | |
import socket | |
import time | |
# pip install requests | |
import requests | |
# pip install PySocks | |
import socks | |
# pip install stem | |
import stem.process | |
from stem import Signal | |
from stem.control import Controller | |
NUM_REQUESTS = 100 | |
SocksPort = 9150 | |
ControlPort = 9151 | |
URL_GEO_IP = 'http://www.telize.com/geoip' | |
DataDirectory = r'C:\Risk\Software\Tor\Browser\TorBrowser\Data\Tor' | |
GeoIPFile = r'C:\Risk\Software\Tor\Browser\TorBrowser\Data\Tor\geoip' | |
GeoIPv6File = r'C:\Risk\Software\Tor\Browser\TorBrowser\Data\Tor\geoip6' | |
# https://www.torproject.org/docs/tor-manual.html.en | |
# https://stem.torproject.org/_modules/stem/process.html | |
tor_process = stem.process.launch_tor_with_config( | |
config = { | |
'DataDirectory': DataDirectory, | |
'GeoIPFile': GeoIPFile, | |
'GeoIPv6File': GeoIPv6File, | |
'AvoidDiskWrites': '1', | |
'SocksPort': str(SocksPort), | |
'ControlPort': str(ControlPort), | |
}, | |
# Just print the message | |
init_msg_handler = print | |
) | |
controller = Controller.from_port(port = ControlPort) | |
socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', SocksPort) | |
IP = set() | |
t0 = time.time() | |
try: | |
controller.authenticate() | |
# Replace the default socket to one with SOCKS for requests | |
socket.socket = socks.socksocket | |
for t in range(NUM_REQUESTS): | |
r = requests.get(URL_GEO_IP) | |
geoip = r.json() | |
IP.add(geoip['ip']) | |
print('[{}] {} {}, {}, {}'.format( | |
t + 1, | |
geoip['ip'] if 'ip' in geoip else '(unknown IP)', | |
geoip['isp'] if 'isp' in geoip else '(unknown ISP)', | |
geoip['city'] if 'city' in geoip else '(unknown city)', | |
geoip['country'] if 'country' in geoip else '(unknown country)' | |
)) | |
# https://stem.torproject.org/api/control.html#stem.Signal | |
controller.signal(Signal.HUP) | |
finally: | |
controller.close() | |
tor_process.kill() | |
total_time = time.time() - t0 | |
print('{} requests made from {} distinct IP addresses.'.format(NUM_REQUESTS, len(IP))) | |
print('Average time for each request: {:g}s.'.format(total_time / NUM_REQUESTS)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment