Mongodb 配置用戶

安裝mongodb4.0參考:

https://blog.csdn.net/gaokcl/article/details/83587077

一,Mongodb 配置用戶

1,配置原因:
MongoDB  域名:端口號  便可以登錄,不安全
2,進入mongodb shell
$ mongo --port 27017  

或者

$ cd /usr/local/mongodb/bin
$ mongo
3, 創建一個超級用戶
> use admin
> db.createUser(
  {
    user: "root",
    pwd: "123456",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
4, 驗證用戶是否存在
# 退出 入mongo shell :ctrl + c

$ mongod --auth       # 重啓 mongo
$ mongo --port 27017  # 進入mongo shell

> db.auth('root','123456')   # 驗證用戶是否存在
1      # 成功標識

5,啓用身份驗證

修改mongodb的配置文件( /usr/local/mongodb/bin/mongodb.conf )

# bindIp改爲0.0.0.0這樣外網也能訪問(默認是127.0.0.1,只能在內網訪問)
net:
  port: 27017
  bindIp: 0.0.0.0

#啓用身份驗證配置
security:
  authorization: enabled

vi /usr/local/mongodb/bin/mongodb.conf

dbpath=/usr/local/mongodb/data/db
logpath=/usr/local/mongodb/logs/mongodb.log
port=27017
logappend=true
fork=true
bind_ip=0.0.0.0

authorization: enabled

#auth=true

重啓mongodb服務

$ sudo service mongod restart  或者  mongod --auth

用密碼連接mongodb

# 嘗試用密碼連接mongodb服務(命令執行完成後,輸入密碼就可以連接成功,進入mongodb shell)

$ mongo --port 27017 -u "root" --authenticationDatabase "admin" -p123456

mongodb4.0配置 /usr/local/mongodb/bin/mongodb.conf :

# mongodb.conf
# for documentation of all options,see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /usr/local/mongodb/logs/mongodb.log

# where and how to store data.
storage:
  dbPath: /usr/local/mongodb/data/db
  journal:
    enabled: true

# how the process runs
processManagement:
  fork: true
# 啓用身份驗證配置
security:
  authorization: enabled
  
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

Mongo DB: Authentication failed錯誤:

參考 :https://blog.csdn.net/qq_38289815/article/details/90579721
https://www.cnblogs.com/timelesszhuang/p/5668589.html


$ cd /usr/local/mongodb/bin

# 創建用戶 ( root 和 test)
use admin
db.createUser({user:"root",pwd:"123456",roles:[{role:"root",db:"admin"}]});
db.createUser({user:"test",pwd:"test",roles:[{role:"root",db:"admin"}]});

或者
use admin
db.shutdownServer();


# 使用創建的用戶名和密碼重新登錄
$ cd /usr/local/mongodb/bin
$ mongo -u "root" -p "123456" --authenticationDatabase "admin"
或者
$ mongo -u "test" -p "test" --authenticationDatabase "admin"

# 刪除
rm -f /usr/local/mongodb/data/db/mongod.lock

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章