Last active
March 30, 2025 14:04
-
-
Save rafa-br34/4207dbc2bb00148badd1b750b4261fc7 to your computer and use it in GitHub Desktop.
A simple class that can be used to interact with TOR
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
import requests | |
import stem.process | |
import stem.control | |
import stem | |
import time | |
from stem import Signal | |
class Router: | |
def __init__(self, control_port, socket_port): | |
self.last_ident_change = 0 | |
self.control_port = control_port | |
self.socket_port = socket_port | |
self.tor_process = None | |
self.controller = None | |
def start(self, data_directory, restart=False, log_path=None): | |
if self.tor_process: | |
if restart: | |
self.tor_process.terminate() | |
else: | |
return | |
self.tor_process = stem.process.launch_tor_with_config({ | |
"ControlPort": str(self.control_port), | |
"SocksPort": str(self.socket_port), | |
"DataDirectory": data_directory, | |
"Log": [ | |
log_path and f"NOTICE file {log_path}" or "NOTICE stdout", | |
log_path and f"ERR file {log_path}" or "ERR stdout", | |
] | |
}) | |
controller = self.controller = stem.control.Controller.from_port("127.0.0.1", port=self.control_port) | |
controller.authenticate() | |
def change_ident_avail(self): | |
return self.controller.is_newnym_available() | |
def change_ident_wait(self): | |
return self.controller.get_newnym_wait() | |
def change_ident(self, block = True): | |
if not self.change_ident_avail(): | |
if block: | |
time.sleep(self.change_ident_wait()) | |
else: | |
return False | |
self.controller.signal(Signal.NEWNYM) | |
self.last_ident_change = time.time() | |
return True | |
def stop(self): | |
if self.tor_process: | |
self.tor_process.terminate() | |
def proxies(self): | |
return { | |
"https": f"socks5://localhost:{self.socket_port}", | |
"http": f"socks5://localhost:{self.socket_port}", | |
} | |
router = Router(7001, 7002) | |
router.start(".data/") | |
print(requests.get("https://echo.free.beeceptor.com/", proxies = router.proxies()).json()) | |
router.change_ident() | |
print(requests.get("https://echo.free.beeceptor.com/", proxies = router.proxies()).json()) | |
router.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment