Skip to content

Instantly share code, notes, and snippets.

@gormih
Created December 31, 2019 16:45
Show Gist options
  • Save gormih/54fd74d45b4f97766aed70bbe40163c7 to your computer and use it in GitHub Desktop.
Save gormih/54fd74d45b4f97766aed70bbe40163c7 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import requests
from stem import Signal
from stem.control import Controller
import time
class TorSession(object):
def __init__(self, proxy_url='socks5://127.0.0.1',
proxy_port=9150,
controller_port=9151,
password="password"):
px = f'{proxy_url}:{proxy_port}'
self.proxies = {'http': px,
'https': px}
self.controller_port = controller_port
self.password = password
def get_new_with_ip(self):
session = requests.sessions.session()
session.proxies.update(self.proxies)
with Controller.from_port(port=self.controller_port) as controller:
controller.authenticate(password=self.password)
controller.signal(Signal.NEWNYM)
time.sleep(controller.get_newnym_wait())
return session
@gormih
Copy link
Author

gormih commented Dec 31, 2019

Example:

`
s_obj = TorSession()

    for i in range(1000):

        ses = s_obj.get_new_with_ip()

        print(ses.get("http://httpbin.org/ip").json()['origin'])

        s_obj.get_new_with_ip()`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment