简体   繁体   English

PyMongo MongoClient SSH连接

[英]PyMongo MongoClient SSH Connection

I'm trying to establish a connection with a MongoDB database via an SSH connection programmatically from python. 我正在尝试通过python以编程方式通过SSH连接与MongoDB数据库建立连接。 I can create a MongoClient object to connect locally but I can't see how to establish an SSH connection for my MongoClient to use. 我可以创建一个MongoClient对象以在本地连接,但看不到如何建立供我的MongoClient使用的SSH连接。

How would I do this? 我该怎么做?

First make sure you have no local MongoDB running on your machine, then ssh to the server where MongoDB is running: 首先确保您的计算机上没有运行本地MongoDB,然后SSH到运行MongoDB的服务器:

ssh -L 27017:MYHOST:27017 MYUSER@MYHOST

Replace MYUSER and MYHOST with your username and host. 用您的用户名和主机替换MYUSER和MYHOST。 Then, in another terminal window, run the "mongo" shell from your local computer. 然后,在另一个终端窗口中,从本地计算机运行“ mongo” shell。 By default it connects to localhost:27017, which you've port-forwarded to the remote host. 默认情况下,它连接到本地主机:27017,您已将其端口转发到远程主机。 The "mongo" shell should connect correctly. “ mongo”外壳应该正确连接。

Then, create a PyMongo connection normally in Python: 然后,通常在Python中创建一个PyMongo连接:

>>> from pymongo import MongoClient
>>> c = MongoClient()
>>> c.test.command('buildinfo')
...

More info about SSH tunneling here: 有关SSH隧道的更多信息,请参见:

https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding

This is not MongoDB-specific at all, any network protocol can be tunneled with SSH port-forwarding. 这根本不是MongoDB特有的,任何网络协议都可以通过SSH端口转发建立隧道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM