diff --git a/plugins/mongodb/index.py b/plugins/mongodb/index.py index e49f1f910..a35fdd001 100755 --- a/plugins/mongodb/index.py +++ b/plugins/mongodb/index.py @@ -203,20 +203,48 @@ def mongdbClientS(): client = pymongo.MongoClient(host=ip, port=int(port), username='root', password=mg_root, authSource='admin') return client +def getMongoDBVersion(): + '''获取MongoDB版本号''' + import pymongo + port = getConfPort() + ip = getConfLocalIp() + try: + # 先不使用认证连接 + client = pymongo.MongoClient(host=ip, port=int(port), serverSelectionTimeoutMS=5000) + db = client.admin + serverStatus = db.command('serverStatus') + version = serverStatus.get('version', '4.0') + client.close() + return version + except Exception as e: + # 如果无法获取版本,默认返回 4.0(新版本兼容模式) + return '4.0' + +def isMongoDB3x(): + '''判断是否为MongoDB 3.x版本''' + version = getMongoDBVersion() + # 匹配 3.x 版本 + if version.startswith('3.'): + return True + return False + def mongdbClient(): import pymongo port = getConfPort() auth = getConfAuth() ip = getConfLocalIp() mg_root = pSqliteDb('config').where('id=?', (1,)).getField('mg_root') - # print(ip,port,auth,mg_root) + if auth == 'disabled': client = pymongo.MongoClient(host=ip, port=int(port)) else: - # uri = "mongodb://root:"+mg_root+"@127.0.0.1:"+str(port) - # client = pymongo.MongoClient(uri) - # 使用 admin 数据库进行认证,兼容 MongoDB 3.0 - client = pymongo.MongoClient(host=ip, port=int(port), username='root', password=mg_root, authSource='admin') + # 根据MongoDB版本选择认证方式 + if isMongoDB3x(): + # MongoDB 3.x 使用 authSource 指定认证数据库 + client = pymongo.MongoClient(host=ip, port=int(port), username='root', password=mg_root, authSource='admin') + else: + # MongoDB 4.x+ 默认在 admin 数据库认证 + client = pymongo.MongoClient(host=ip, port=int(port), username='root', password=mg_root) return client