参考:https://blog.csdn.net/weixin_41003801/article/details/88638161
本文:
import pymongo from sshtunnel import SSHTunnelForwarder def get_mongodb_client(): ssh_address_or_host = (" ",22) ##服务器地址与ssh_port ssh_username = "root" ##登录服务器的用户 ssh_password = " " ##登录服务器的密码 remote_bind_address = ' ' # mongo_user = 'xxxx' ## 访问数据库的用户名 # mongo_password = 'xxxxx' #访问数据库的密码 server = SSHTunnelForwarder( ssh_address_or_host=ssh_address_or_host, ssh_username = ssh_username, ssh_password = ssh_password , remote_bind_address = (remote_bind_address,27017)) # 打开守护线程 server.daemon_forward_servers = True server.start() print(server.local_bind_port) client = pymongo.MongoClient('127.0.0.1',server.local_bind_port) ## 这里一定要填入ssh映射到本地的端口 db = client['REL'] collection = db['res'] print(collection.find_one()) server.close() return client get_mongodb_client()