天天看點

Python 使用者驗證連接配接MongoDB

1.登入資料庫,建立登入使用者密碼

[root@mongodb bin]# pwd

12345678 /opt/mongodb/bin[root@mongodb bin]# ./mongo> use adminswitched to db admin> db.createUser({user:"root",pwd:"123456",roles:["root"]})    #建立資料庫管理者賬号密碼Successfully added user: { "user" : "root", "roles" : [ "root" ] }> exitbye

2.配置檔案開啟驗證後重新開機mongodb服務

1234 [root@mongodb ~]# vim /opt/mongodb/data/mongodb.conf #開啟認證auth = true[root@mongodb ~]# service mongodb restart

3.編寫腳本

[root@mongodb ~]#  cat auth_mongodb.py 

#coding=utf-8
#導入子產品
from pymongo import MongoClient 
#建立連接配接
client=MongoClient("localhost",27017)
#資料庫名admin
db=client.admin
#認證使用者密碼
db.authenticate('root','123456')
#建立集合和資料
db.test.insert({"name":"this is test"})
col=db.test
#列印資料輸出
for item in col.find():
    print item
#關閉連接配接
client.close()           

複制

4.執行腳本

Python 使用者驗證連接配接MongoDB

5.驗證:進庫檢視是否有資料

Python 使用者驗證連接配接MongoDB

sucess!!!!