59 lines
1.8 KiB
Python
Executable File
59 lines
1.8 KiB
Python
Executable File
# -*-mode: python; py-indent-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*-
|
|
|
|
import os
|
|
import sys
|
|
import getpass
|
|
import socket
|
|
|
|
from stem.control import EventType, Controller
|
|
from stem.connection import MissingPassword
|
|
|
|
def set_socks_proxy(SOCKS5_PROXY_HOST='127.0.0.1', SOCKS5_PROXY_PORT=9050):
|
|
try:
|
|
import socks # you need to install pysocks (see above)
|
|
# Remove this if you don't plan to "deactivate" the proxy later
|
|
default_socket = socket.socket
|
|
|
|
# Set up a proxy
|
|
socks.set_default_proxy(socks.SOCKS5, SOCKS5_PROXY_HOST, SOCKS5_PROXY_PORT)
|
|
socket.socket = socks.socksocket
|
|
except ImportError:
|
|
return False
|
|
return True
|
|
|
|
def get_controller(password=None, address='127.0.0.1', port=9051, unix='/run/tor/control'):
|
|
if unix and os.path.exists(unix):
|
|
# print(unix)
|
|
controller = Controller.from_socket_file(path=unix)
|
|
else:
|
|
# print(port)
|
|
controller = Controller.from_port(address=address, port=port)
|
|
|
|
if password is None:
|
|
# print("DBUG: trying TOR_CONTROLLER_PASSWORD")
|
|
password = os.environ.get('TOR_CONTROLLER_PASSWORD')
|
|
else:
|
|
# print(f"DBUG: using a password {len(password)}")
|
|
pass
|
|
if not password:
|
|
# print("DBUG: trying without a password")
|
|
try:
|
|
controller.authenticate()
|
|
return controller
|
|
except MissingPassword as e:
|
|
if not password:
|
|
sys.stdout.flush()
|
|
password = getpass.unix_getpass(prompt='Controller Password: ', stream=sys.stderr)
|
|
except Exception as e:
|
|
print(f"WARN: {e}")
|
|
try:
|
|
# print(f"DBUG: using a password {password}")
|
|
controller.authenticate(password)
|
|
except Exception as e:
|
|
print(f"ERROR: {e}")
|
|
|
|
return controller
|
|
|
|
|
|
|