Python通过ssh登录服务器并连接云mongodb

一般情况下要远程操作服务器上的mongo,要通过跳板机登录服务器,然后连接mongo,以下是总结出来的使用方式,仅供参考
# -*- coding: utf-8 -*-
# Author  : Cher Chan
# Time    : 2019/3/14 21:02
# File    : test2.py
import pymongo
from sshtunnel import SSHTunnelForwarder

def get_mongodb_client():
    server_addr = "xxx.xxx.xxx.xxx", ##服务器地址
    server_user = "xxx", ##登录服务器的用户
    server_password = "xxxx", ##登录服务器的密码
    mongo_address = "192.168.xx.xx"  ##云mongodb地址
    mongo_port = 27017 #mongo端口,一般默认27017
    mongo_user = 'xxx'  ## 访问数据库的用户名
    mongo_password = 'xxxx'  #访问数据库的密码
    server = SSHTunnelForwarder(
        ssh_address_or_host=server_addr,
        ssh_password=server_password,
        ssh_username=server_user,
        remote_bind_address=(mongo_address, mongo_port))
    server.start()
    uri = "mongodb://%s:%s@%s"  % (
    mongo_user, mongo_password, mongo_address)
    client = pymongo.MongoClient(uri)
    return client
if __name__ == "__main__":
    client = get_mongodb_client()
    users = client.users

你可能感兴趣的:(编程笔记,python,mongo,ssh)