在 CentOS 7 上安装 MongoDB 后,为了保护 MongoDB 数据库的安全,通常需要设置账号密码。下面是设置账号密码的步骤:
启动 MongoDB 服务:
使用以下命令启动 MongoDB 服务:
systemctl start mongod
连接 MongoDB:
使用以下命令连接 MongoDB:
mongo
创建管理员账号:
使用以下命令创建一个名为 admin 的数据库,并创建一个管理员账号:
use admin
db.createUser({user:"admin",pwd:"password",roles:[{role:"root",db:"admin"}]})
其中,user 是管理员账号的用户名,pwd 是管理员账号的密码。
退出 MongoDB:
使用以下命令退出 MongoDB:
quit()
修改 MongoDB 配置文件:
打开 MongoDB 配置文件 /etc/mongod.conf,找到以下行:
#security:
security:
authorization: enabled
将 authorization 改为 enabled,表示启用 MongoDB 认证功能。
重启 MongoDB 服务:
使用以下命令重启 MongoDB 服务:
systemctl restart mongod
连接 MongoDB:
使用以下命令连接 MongoDB:
mongo -u admin -p password --authenticationDatabase admin
其中,-u 表示用户名,-p 表示密码,–authenticationDatabase 表示认证数据库。
创建普通用户:
使用以下命令创建一个名为 test 的数据库,并创建一个普通用户:
use test
db.createUser({user:"testuser",pwd:"testpass",roles:[{role:"readWrite",db:"test"}]})
其中,user 是普通用户的用户名,pwd 是普通用户的密码,roles 表示该用户在 test 数据库中的角色。
退出 MongoDB:
使用以下命令退出 MongoDB:
quit()
现在,您已经成功设置了 MongoDB 账号密码。在连接 MongoDB 时,需要使用管理员账号才能进行管理操作。普通用户只能对其拥有权限的数据库进行读写操作。