Search code examples
pythonmongodbpymongo

how do I use pymongo behind proxy that require authentication


how do I use pymongo behind proxy that require authentication?

I am able to find settings for ssh tunnel servers, such as How to connect remote mongodb with pymongo

But I am working on a environment that is behind a firewall that need to use proxy authentication. How do I config for that? For OSX terminal I use something similar to this:

export http_proxy="username:password@ip address:port number"

I find this new feature for socks5 proxy authentication https://jira.mongodb.org/browse/CSHARP-734, but I am just looking for basic or NTLM authentication methods, is it supported?


Solution

  • I forked pymongo official repo and used python-socks to add http/socks proxy support. Note: DNS resolving still done by pymongo not through proxy.

    If you installed pymongo before you need to remove it first:

    pip uninstall pymongo
    

    Install it with git:

    pip install git+https://github.com/benjamintenny/mongo-python-driver-proxy
    

    Here is an example for your case:

    import os
    import pymongo
    # Set http proxy with credentials
    os.environ["MONGO_PROXY"] = "http://username:password@127.0.0.1:8080"
    # Connect to db as normal
    client = pymongo.MongoClient("your-mongodb-url")
    db = client.test
    print(db.name)