鍍金池/ 問答/數(shù)據(jù)庫  網(wǎng)絡(luò)安全/ pymongo無法連接到mongo集群,連本地沒問題

pymongo無法連接到mongo集群,連本地沒問題

問題描述

pymongo無法連接到mongo集群,連本地沒問題.
用命令行方式一切正常。

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

本地mongo無驗證,集群有權(quán)限驗證,

用命令行方式一切正常

$ mongo localhost
MongoDB shell version: 3.2.20
> db.version()
3.0.6
> use hello
switched to db hello
> db
hello
> db.hello.count() # 數(shù)據(jù)庫、表名都叫hello
7

集群

$ mongo -u user  -p password  remote_ip:remote_port/hello  --authenticationDatabase admin
hello:PRIMARY> db.version()
3.6.4-1.2

pymongo版本為:3.7.1。 嘗試如下:

In [2]: from pymongo import MongoClient

In [3]: c2= MongoClient('mongodb://localhost/hello')

In [4]: db2=c2.get_database()

In [5]: db2['hello'].count()   # 本地mongo一切正常
Out[5]: 7

In [6]: c1=MongoClient("mongodb://user:password@remote_ip:remote_port/hello&authSource=admin")

In [7]: db1=c1.get_database()

In [8]: db1['hello'].count()
/home/work/venv36/bin/ipython:1: DeprecationWarning: count is deprecated. Use estimated_document_count or count_documents instead. Please note that $where must be replaced by $expr, $near must be replaced by $geoWithin with $center, and $nearSphere must be replaced by $geoWithin with $centerSphere
  #!/home/work/fsj/venv36/bin/python3.6
---------------------------------------------------------------------------
OperationFailure                          Traceback (most recent call last)
<ipython-input-8-bf661fbd7e9c> in <module>()
----> 1 db1['hello'].count()

~/fsj/venv36/lib/python3.6/site-packages/pymongo/collection.py in count(self, filter, session, **kwargs)
   1764         collation = validate_collation_or_none(kwargs.pop('collation', None))
   1765         cmd.update(kwargs)
-> 1766         return self._count(cmd, collation, session)
   1767
   1768     def create_indexes(self, indexes, session=None, **kwargs):

~/fsj/venv36/lib/python3.6/site-packages/pymongo/collection.py in _count(self, cmd, collation, session)
   1561     def _count(self, cmd, collation=None, session=None):
   1562         """Internal count helper."""
-> 1563         with self._socket_for_reads(session) as (sock_info, slave_ok):
   1564             res = self._command(
   1565                 sock_info,

/usr/local/lib/python3.6/contextlib.py in __enter__(self)
     79     def __enter__(self):
     80         try:
---> 81             return next(self.gen)
     82         except StopIteration:
     83             raise RuntimeError("generator didn't yield") from None

~/fsj/venv36/lib/python3.6/site-packages/pymongo/mongo_client.py in _socket_for_reads(self, read_preference)
   1099         server = topology.select_server(read_preference)
   1100
-> 1101         with self._get_socket(server) as sock_info:
   1102             slave_ok = (single and not sock_info.is_mongos) or (
   1103                 read_preference != ReadPreference.PRIMARY)

/usr/local/lib/python3.6/contextlib.py in __enter__(self)
     79     def __enter__(self):
     80         try:
---> 81             return next(self.gen)
     82         except StopIteration:
     83             raise RuntimeError("generator didn't yield") from None

~/fsj/venv36/lib/python3.6/site-packages/pymongo/mongo_client.py in _get_socket(self, server)
   1056     def _get_socket(self, server):
   1057         try:
-> 1058             with server.get_socket(self.__all_credentials) as sock_info:
   1059                 yield sock_info
   1060         except NetworkTimeout:

/usr/local/lib/python3.6/contextlib.py in __enter__(self)
     79     def __enter__(self):
     80         try:
---> 81             return next(self.gen)
     82         except StopIteration:
     83             raise RuntimeError("generator didn't yield") from None

~/fsj/venv36/lib/python3.6/site-packages/pymongo/pool.py in get_socket(self, all_credentials, checkout)
   1004         sock_info = self._get_socket_no_auth()
   1005         try:
-> 1006             sock_info.check_auth(all_credentials)
   1007             yield sock_info
   1008         except:

~/fsj/venv36/lib/python3.6/site-packages/pymongo/pool.py in check_auth(self, all_credentials)
    675
    676             for credentials in cached - authset:
--> 677                 auth.authenticate(credentials, self)
    678                 self.authset.add(credentials)
    679

~/fsj/venv36/lib/python3.6/site-packages/pymongo/auth.py in authenticate(credentials, sock_info)
    561     mechanism = credentials.mechanism
    562     auth_func = _AUTH_MAP.get(mechanism)
--> 563     auth_func(credentials, sock_info)
    564
    565

~/fsj/venv36/lib/python3.6/site-packages/pymongo/auth.py in _authenticate_default(credentials, sock_info)
    538             return _authenticate_scram(credentials, sock_info, 'SCRAM-SHA-1')
    539     elif sock_info.max_wire_version >= 3:
--> 540         return _authenticate_scram(credentials, sock_info, 'SCRAM-SHA-1')
    541     else:
    542         return _authenticate_mongo_cr(credentials, sock_info)

~/fsj/venv36/lib/python3.6/site-packages/pymongo/auth.py in _authenticate_scram(credentials, sock_info, mechanism)
    260                ('payload', Binary(b"n,," + first_bare)),
    261                ('autoAuthorize', 1)])
--> 262     res = sock_info.command(source, cmd)
    263
    264     server_first = res['payload']

~/fsj/venv36/lib/python3.6/site-packages/pymongo/pool.py in command(self, dbname, spec, slave_ok, read_preference, codec_options, check, allowable_errors, check_keys, read_concern, write_concern, parse_write_concern_error, collation, session, client, retryable_write, publish_events)
    577                            compression_ctx=self.compression_context,
    578                            use_op_msg=self.op_msg_enabled,
--> 579                            unacknowledged=unacknowledged)
    580         except OperationFailure:
    581             raise

~/fsj/venv36/lib/python3.6/site-packages/pymongo/network.py in command(sock, dbname, spec, slave_ok, is_mongos, read_preference, codec_options, session, client, check, allowable_errors, address, check_keys, listeners, max_bson_size, read_concern, parse_write_concern_error, collation, compression_ctx, use_op_msg, unacknowledged)
    148                 helpers._check_command_response(
    149                     response_doc, None, allowable_errors,
--> 150                     parse_write_concern_error=parse_write_concern_error)
    151     except Exception as exc:
    152         if publish:

~/fsj/venv36/lib/python3.6/site-packages/pymongo/helpers.py in _check_command_response(response, msg, allowable_errors, parse_write_concern_error)
    153
    154             msg = msg or "%s"
--> 155             raise OperationFailure(msg % errmsg, code, response)
    156
    157

OperationFailure: Authentication failed.

按照文檔https://api.mongodb.com/pytho... 檢查沒問題。

本地是3.0,集群3.6,authentication mechanism 都應(yīng)該是默認(rèn)的SCRAM-SHA-1

請問怎么處理呢

回答
編輯回答
尤禮
  1. 檢查密碼中是不是有特殊符號,比如@,:之類的
  2. 從堆棧中看用的是SCRAM-SHA-1認(rèn)證,檢查一下你的賬號是不是MONGODB-CR
use admin
db.system.users.find()
2017年9月9日 01:47