Search code examples
pythonmongodbdnstor

Connect to localhost mongodb from python script started by torify


When I'm trying to connect to the mongodb from my python script I see this warning many times and error finally:

[Dec 13 11:58:56] WARNING torsocks[8133]: [connect] Connection to a local address are denied since it might be a TCP DNS query to a local DNS server. Rejecting it for safety reasons. (in tsocks_connect() at connect.c:177)

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 1] Operation not permitted

I use torify command for starting my command - torify python myscript.py. Without torify it works.

What I'm doing wrong? The same situation is on another machines to.


Solution

  • I found a solution for this case. I have to create a Hidden Service first. To do that I have to add this lines to my tor config file (/etc/tor/torrc):

    HiddenServiceDir /tmp/tormongo
    HiddenServicePort 27017 127.0.0.1:27017
    

    After that I need to restart my tor service. If everything was done right the folder has to appear in /tmp. In this folder will be the new file hostname with the string like sgwqrpepus3lwcke.onion. This is the host what I can use instead of localhost in mongodb connection settings.

    Or I can add a new ENV variable for this setting and set it every script start by using command like that:

    export DB_HOST=$(cat /tmp/tormongo/hostname) && torify python /var/www/myproject/myscript.py