Tor 的新名称(信号 NEWNYM)不适用于 Python 和 UWSGI

问题描述 投票:0回答:0

我在 python 中有一个服务器,它创建了一个新的 Tor 进程实例,并循环 5 次打印和更新 IP。

def get_tor_session():
    session = requests.session()
    session.proxies['https'] = 'socks5://localhost:9050'
    session.proxies['http'] = 'socks5://localhost:9050'
    return session

def renew_connection():
    print("Renewing connection")
    torControl.signal(Signal.NEWNYM)
    time.sleep(torControl.get_newnym_wait()) 

def startTor(config):
    GEOIPFILE_PATH = "/usr/share/tor/geoip"
    try:    
        urllib.request.urlretrieve('https://raw.githubusercontent.com/torproject/tor/main/src/config/geoip', GEOIPFILE_PATH)
        print ("GeoIP file updated")
    except Exception as e:
        print ('[INFO] Unable to update geoip file. Using local copy.', e)
    try:
        # start tor
        print("Starting tor")
        torProcess = launch_tor_with_config(
            config=config,  # use our custom config
            tor_cmd='tor',  # start tor normally
            completion_percent=100,  # blocks until tor is 100%
            timeout=90,  # wait 90 sec for tor to start
            take_ownership=True  # subprocess will close with parent
        )
        # connect a controller
        print("Connecting controller")
        torControl = Controller.from_port(
            address="127.0.0.1", port=int(config['ControlPort']))
        # auth controller
        torControl.authenticate(password='somepass')
        print("Connected to tor process")
        return torProcess, torControl

    except Exception as e:
        print(e)```


config = {
    'ClientOnly': '1',
    'ControlPort': '9051',
    'DataDirectory': '/tmp/tor',
    'GeoIPFile': '/usr/share/tor/geoip',
    'EntryNodes': '{UK}',
    'ExitNodes': '{UK}',
    'HashedControlPassword':'16:489A6B09FB6D0E9D601D22CFCF438DB9832E7584450E4AF1F0709FF8FB'}


torProcess, torControl = startTor(config)

然后我调用一个函数,其中有一个循环打印 IP 地址并更新它。

for i in range(5):
        session = get_tor_session()
        print(f"trying: {i}")      
        print(session.get('http://icanhazip.com/', timeout=5).text)
        renew_connection()        

我有一个 python 虚拟环境,我可以在其中运行文件 (python app.py),一切都会运行良好。 IP 将毫无问题地打印和更新。

但是,我想使用 uwsgi 和 nginx 在后台运行它,但我无法让它工作。在第一个循环中,IP 将被正确打印,但程序在更新时挂起(在打印“Renewing connection”之后)。知道我做错了什么吗?会不会跟Linux和文件/目录权限有关?没有出现错误(我尝试将整个函数包装在一个 try-catch 中),只是程序挂在那里直到 harakiri 杀死 uwsgi worker。我尝试在不同时间设置超时但没有任何运气。

python sockets ip uwsgi tor
© www.soinside.com 2019 - 2024. All rights reserved.