登入 MongoDB shell 並切換到 admin 庫
mongo
use admin
建立管理使用者
db.createUser(
{
user: "yourusername",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
修改 /etc/init.d/mongod 並重啟 MongoDB
OPTIONS=" -f $CONFIGFILE"
改為
OPTIONS=" --auth -f $CONFIGFILE"
/etc/init.d/mongod restart
登入並進行使用者認證
mongo
use admin
db.auth("yourusername", "password")
也可以這樣登入
mongo --port 27017 -u yourusername -p password --authenticationDatabase admin
認證成功後,建立普通使用者,使用此使用者登陸後即可對指定資料庫進行操作
db.createUser(
{
user: "123",
pwd: "123123",
roles: [
{ role: "readWrite", db: "firstdb" }, # firstdb 庫給予讀寫權限
{ role: "read", db: "products" }, # products 庫給予讀許可權
]
}
)
使用 PyMongo 串連使用使用者認證的 mongodb
from pymongo import MongoClient
MongoClient('mongodb://user:' + 'password' + '@127.0.0.1')
如果密碼中含有 %,\,/ 等符號,需要使用 urllib 進行轉義
import urllib
from pymongo import MongoClient
password = urllib.quote_plus('pass/word%&\/')
MongoClient('mongodb://user:' + password + '@127.0.0.1')
修改指定使用者的密碼
use admin
db.changeUserPassword("username", "newpassword")
刪除指定使用者
use admin
db.db.system.users.remove({user:"username"})