没有管理员用户的话就先建一个
# /usr/local/mongodb/bin/mongo --host localhost --port 27017 rs:PRIMARY> use admin switched to db admin rs:PRIMARY> db.createUser({ ... "user": "root", ... "pwd": "密码", ... "roles": [ ... { ... "role": "userAdminAnyDatabase", ... "db": "admin" ... }, ... { ... "role": "readWriteAnyDatabase", ... "db": "admin" ... }, ... { ... "role": "dbAdmin", ... "db": "admin" ... }, ... { ... "role": "root", ... "db": "admin" ... } ... ] ... });
生成协同文件传输到集群每个节点
# openssl rand -base64 512 > /usr/local/mongodb/access.key # chmod 0600 /usr/local/mongodb/access.key
修改配置文件
cat >> /usr/local/mongodb/mongod.conf << EOF auth=true keyFile=/usr/local/mongodb/access.key EOF
重启MongoDB
root用户登录验证
# /usr/local/mongodb/bin/mongo localhost:27017/admin -u root -p
添加普通用户
rs:PRIMARY> use 库名 rs:PRIMARY> db.createUser({ ... user:"用户名", ... pwd:"密码", ... roles:[ ... {role:"readWrite",db:"库名"} ... ] ... });