MongoDB默认是不认证的,默认没有账号,只要能连接上服务就可以对数据库进行各种操作,MongoDB认为安全最好的方法就是在一个可信的环境中运行它,保证之后可信的机器才能访问它,可能这些对一些要求高的环境,安全还不够。MongoDB提供用户认证,需要在启动时加上--auth开启认证。
一、MongoDB安装
Mongodb各版本下载地址:https://www.mongodb.org/dl/linux/x86_64-rhel62 本案例的Mongodbv3.2百度下载地址:https://pan.baidu.com/s/194ef261BpcypxzAl9aRaQg 提取密码:tv8m 下载放到服务器的/usr/local/src目录下 1.1)安装MongoDB [root@MongoDB-server ~]# cd /usr/local/src/ [root@MongoDB-server src]# ll mongodb-linux-x86_64-rhel62-v3.2-latest.tgz -rw-r--r-- 1 root root 86699142 Nov 22 2017 mongodb-linux-x86_64-rhel62-v3.2-latest.tgz [root@MongoDB-server src]# tar -zvxf mongodb-linux-x86_64-rhel62-v3.2-latest.tgz [root@MongoDB-server src]# mv mongodb-linux-x86_64-rhel62-3.2.17-34-g4c1bae566c /usr/local/mongodb [root@MongoDB-server src]# ll /usr/local/mongodb //Mongodb主目录 total 100 drwxr-xr-x 2 root root 4096 Sep 20 22:33 bin -rw-r--r-- 1 root root 34520 Nov 21 2017 GNU-AGPL-3.0 -rw-r--r-- 1 root root 16726 Nov 21 2017 MPL-2 -rw-r--r-- 1 root root 2262 Nov 21 2017 README -rw-r--r-- 1 root root 35910 Nov 21 2017 THIRD-PARTY-NOTICES [root@MongoDB-server src]# mkdir /usr/local/mongodb/data //Mongodb数据目录,可以存放在一个独立的大分区上 [root@MongoDB-server src]# mkdir /usr/local/mongodb/log //Mongodb日志目录 1.2)启动MongoDB 使用mongod命令建立一个mongodb数据库链接,数据库的路径为/usr/local/mongodb/data,日志路径为/usr/local/mongodb/log/mongo.log mongodb的启动程序放在后台执行,下面命令执行后,按ctrl+c。 [root@MongoDB-server src]# nohup /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log & ========================================== mongodb的参数说明: --dbpath 数据库路径(数据文件) --logpath 日志文件路径 --master 指定为主机器 --slave 指定为从机器 --source 指定主机器的IP地址 --pologSize 指定日志文件大小不超过64M.因为resync是非常操作量大且耗时,最好通过设置一个足够大的oplogSize来避免resync(默认的 oplog大小是空闲磁盘大小的5%)。 --logappend 日志文件末尾添加 --port 启用端口号 --fork 在后台运行 --only 指定只复制哪一个数据库 --slavedelay 指从复制检测的时间间隔 --auth 是否需要验证权限登录(用户名和密码) ========================================== [root@MongoDB-server src]# ps -ef|grep mongodb root 13216 10204 0 22:38 pts/1 00:00:00 /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log root 14185 10204 0 22:42 pts/1 00:00:00 grep mongodb MongoDB默认端口是27017,启动后,等一会儿端口就会起来。如果启动后,发现端口没有起来,可以查看日志/usr/local/mongodb/log/mongo.log [root@MongoDB-server src]# lsof -i:27017 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mongod 13216 root 6u IPv4 4260453 0t0 TCP *:27017 (LISTEN) 1.3)设置mongodb的环境变量 [root@MongoDB-server src]# vim /etc/profile ...... export PATH=$PATH:/usr/local/mongodb/bin/ [root@MongoDB-server src]# source /etc/profile [root@MongoDB-server src]# mongod --version db version v3.2.17-34-g4c1bae566c git version: 4c1bae566c0c00f996a2feb16febf84936ecaf6f OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013 allocator: tcmalloc modules: none build environment: distmod: rhel62 distarch: x86_64 target_arch: x86_64 1.4)为了更方便的启动和关闭MongoDB,可以使用Shell写脚本,当然也可以加入到service中。更好的方式是采用配置文件,把MongoDB需要的参数写入配置文件, 然后在脚本中引用; [root@MongoDB-server src]# vim /usr/local/mongodb/mongodb.conf #代表端口号,如果不指定则默认为27017 port=27017 #绑定ip bind_ip=0.0.0.0 #MongoDB数据文件目录 dbpath=/usr/local/mongodb/data #MongoDB日志文件目录 logpath=/usr/local/mongodb/log/mongo.log #日志文件自动累加 logappend=true 编写MongoDB启动脚本 [root@MongoDB-server src]# vim /etc/init.d/mongodb #!/bin/bash # # mongod Start up the MongoDB server daemon # # source function library . /etc/rc.d/init.d/functions #定义命令 CMD=/usr/local/mongodb/bin/mongod #定义配置文件路径 INITFILE=/usr/local/mongodb/mongodb.conf start() { #&表示后台启动,也可以使用fork参数 $CMD -f $INITFILE & echo "MongoDB is running background..." } stop() { pkill mongod echo "MongoDB is stopped." } case "$1" in start) start ;; stop) stop ;; *) echo $"Usage: $0 {start|stop}" esac 授予脚本可执行权限 [root@MongoDB-server src]# chmod 755 /etc/init.d/mongodb [root@MongoDB-server src]# /etc/init.d/mongodb status Usage: /etc/init.d/mongodb {start|stop} [root@MongoDB-server src]# /etc/init.d/mongodb stop Terminated [root@MongoDB-server src]# lsof -i:27001 [1]+ Done nohup /usr/local/mongodb/bin/mongod --dbpath=/usr/local/mongodb/data/ --logpath=/usr/local/mongodb/log/mongo.log [root@MongoDB-server src]# lsof -i:27001 [root@MongoDB-server src]# /etc/init.d/mongodb start MongoDB is running background... [root@MongoDB-server src]# ps -ef|grep mongodb root 16060 1 2 22:49 pts/1 00:00:00 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf root 16205 10204 0 22:49 pts/1 00:00:00 grep mongodb [root@MongoDB-server ~]# lsof -i:27001 [root@MongoDB-server ~]# 启动后发现27017端口没有起来,查看日志: [root@MongoDB-server src]# tail -f /usr/local/mongodb/log/mongo.log ...... 2018-09-20T22:55:46.236+0800 I NETWORK [initandlisten] waiting for connections on port 27017 2018-09-20T22:55:46.290+0800 W NETWORK [HostnameCanonicalizationWorker] Failed to obtain address information for hostname MongoDB-server: Name or service not known 2018-09-20T22:55:47.014+0800 I FTDC [ftdc] Unclean full-time diagnostic data capture shutdown detected, found interim file, some metrics may have been lost. OK 原因:获取不到地址对应的主机名,这一般与HOSTS有关 解决办法: [root@MongoDB-server ~]# ifconfig|grep "inet addr"|grep Bcast|awk -F":" '{print $2}'|awk '{print $1}' 192.168.10.205 [root@MongoDB-server ~]# hostname MongoDB-server [root@MongoDB-server ~]# vim /etc/hosts [root@MongoDB-server ~]# echo "192.168.10.205 MongoDB-server" >> /etc/hosts [root@MongoDB-server ~]# cat /etc/hosts ...... 192.168.10.205 MongoDB-server 再次启动 [root@MongoDB-server ~]# ps -ef|grep mongodb root 17789 1 0 22:55 pts/0 00:00:01 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf root 18933 16606 0 23:00 pts/0 00:00:00 grep mongodb [root@MongoDB-server ~]# kill -9 16890 [root@MongoDB-server ~]# ps -ef|grep mongodb root 18979 16606 0 23:00 pts/0 00:00:00 grep mongodb [root@MongoDB-server ~]# /etc/init.d/mongodb start MongoDB is running background... [root@MongoDB-server ~]# ps -ef|grep mongodb root 17789 1 0 22:55 pts/0 00:00:01 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf root 19132 16606 0 23:00 pts/0 00:00:00 grep mongodb [root@MongoDB-server ~]# lsof -i:27017 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mongod 17789 root 6u IPv4 4289555 0t0 TCP *:27017 (LISTEN) 连接MongoDB服务 [root@MongoDB-server src]# mongo 127.0.0.1:27017 或者直接使用mongo命令进行连接,默认连接的就是127.0.0.1:27017 MongoDB shell version: 3.2.17-34-g4c1bae566c connecting to: 127.0.0.1:27017/test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: 2018-09-20T22:55:46.232+0800 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended. 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2018-09-20T22:55:46.233+0800 I CONTROL [initandlisten] > help db.help() help on db methods db.mycoll.help() help on collection methods sh.help() sharding helpers rs.help() replica set helpers help admin administrative help help connect connecting to a db help help keys key shortcuts help misc misc things to know help mr mapreduce show dbs show database names show collections show collections in current database show users show users in current database show profile show most recent system.profile entries with time >= 1ms show logs show the accessible logger names show log [name] prints out the last segment of log in memory, 'global' is default use <db_name> set current database db.foo.find() list objects in collection foo db.foo.find( { a : 1 } ) list objects in foo where a == 1 it result of the last line evaluated; use to further iterate DBQuery.shellBatchSize = x set default number of items to display on shell exit quit the mongo shell > show dbs local 0.000GB >
二、MongoDB认证
MongoDB Roles(内置角色)
- 数据库用户角色:read、readWrite;
- 数据库管理角色:dbAdmin、dbOwner、userAdmin;
- 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
- 备份恢复角色:backup、restore;
- 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
- 超级用户角色:root
- 这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwner 、userAdmin、userAdminAnyDatabase)
- 内部角色:__system
具体角色
- Read:允许用户读取指定数据库
- readWrite:允许用户读写指定数据库
- dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
- userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
- clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
- readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
- readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
- userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
- dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
- root:只在admin数据库中可用。超级账号,超级权限
认证操作实例如下
初始化数据库的时候,一定要先禁止用户验证功能,然后在创建管理用户,之后就可以开启验证,操作数据库了。
MongoDB认证前需要添加账号,添加管理员账号(默认情况下系统中没有用户) 谨记:先在不开启认证的情况下,创建用户,之后关闭服务,然后再开启认证,才生效!!!! [root@MongoDB-server src]# mongo 127.0.0.1:27017 ...... 切换到admin库 > use admin switched to db admin 添加超级用户 > use admin switched to db admin > db.system.users.find(); > db.addUser("admin","1234!@#$qwer"); 2018-09-21T09:59:56.125+0800 E QUERY [thread1] TypeError: db.addUser is not a function : @(shell):1:1 如上创建用户报错:报错addUser is not a function 经过排查原因,由于MongDB3.x版本已经不再支持addUser()方法,用createUser()方法取而代之。 特别注意的是:创建用户以及设置密码时,role角色里面一定要跟role、db参数,认证时对应的库一定要搞清楚! admin管理员授权时,role角色最好设置成root,否则认证后可能会有些命令执行不了。 > db.createUser({user: "admin",pwd: "1234!@#$qwer",roles:[{"role":"root","db":"admin"}]}); Successfully added user: { "user" : "admin", "roles" : [ { "role" : "root", "db" : "admin" } ] } > 查询添加的用户(必须要先切换到admin库下进行查看) > db.system.users.find(); { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "tnnpiLjweUJWR1mQzC/cuw==", "storedKey" : "Q7G7KqfYQa3eKcHOSsSkxGs2Ci0=", "serverKey" : "GKOG66hhf6DkXNrTmHWGoFHxXFo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] } 添加普通账号 切换到kevin库添加普通用户(readWrite有读写权限;read有读权限) > use kevin; switched to db kevin > db.createUser({user: "kevin",pwd: "kevin@123456",roles:[{"role":"readWrite","db":"kevin"}]}); Successfully added user: { "user" : "kevin", "roles" : [ { "role" : "readWrite", "db" : "kevin" } ] } > use grace; switched to db grace > db.createUser({user: "grace",pwd: "grace@123",roles:[{"role":"read","db":"grace"}]}); Successfully added user: { "user" : "grace", "roles" : [ { "role" : "read", "db" : "grace" } ] } 查询添加的用户(必须要先切换到admin库下进行查看) > use admin; switched to db admin > db.system.users.find(); { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "tnnpiLjweUJWR1mQzC/cuw==", "storedKey" : "Q7G7KqfYQa3eKcHOSsSkxGs2Ci0=", "serverKey" : "GKOG66hhf6DkXNrTmHWGoFHxXFo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] } { "_id" : "kevin.kevin", "user" : "kevin", "db" : "kevin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "u3RgCHmt3AfigOIVNKy7OA==", "storedKey" : "Je7SP6SohGPZSb3VBXOJkNlXz20=", "serverKey" : "5laXjac6NfpYuivcmK3SK0GohRo=" } }, "roles" : [ { "role" : "readWrite", "db" : "kevin" } ] } { "_id" : "grace.grace", "user" : "grace", "db" : "grace", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "9xLjmg7Q8YsZ1Y9vF71P6g==", "storedKey" : "tID4qA9AaJ4IIOgbC1oHZZYqVdg=", "serverKey" : "ayvaN6QkDUOz1KUs+SG3S8IyvAo=" } }, "roles" : [ { "role" : "read", "db" : "grace" } ] } > 删除用户 > use admin; switched to db admin > db.system.users.remove({user:"admin"}) WriteResult({ "nRemoved" : 1 }) > db.system.users.remove({user:"kevin"}) WriteResult({ "nRemoved" : 1 }) > db.system.users.remove({user:"grace"}) WriteResult({ "nRemoved" : 1 }) > db.system.users.find(); > 修改用户密码,可以利用db.changeUserPassword进行密码重置!!!!! > use grace; switched to db grace > db.changeUserPassword("grace","grace@1986"); > 以--auth启动mongodb开启认证(或者在配置文件中添加"auth=true") [root@MongoDB-server ~]# vim /usr/local/mongodb/mongodb.conf #代表端口号,如果不指定则默认为27017 port=27017 #绑定ip bind_ip=0.0.0.0 #MongoDB数据文件目录 dbpath=/usr/local/mongodb/data #MongoDB日志文件目录 logpath=/usr/local/mongodb/log/mongo.log #日志文件自动累加 logappend=true #开启MongoDB认证 auth=true [root@MongoDB-server ~]# cat /etc/init.d/mongodb ...... $CMD -f $INITFILE --auth & ...... 重启mongodb [root@MongoDB-server ~]# ps -ef|grep mongodb root 17789 1 0 22:55 pts/0 00:00:06 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf root 25161 16606 0 23:24 pts/0 00:00:00 grep mongodb [root@MongoDB-server ~]# kill -9 17789 [root@MongoDB-server ~]# ps -ef|grep mongodb root 25190 16606 0 23:24 pts/0 00:00:00 grep mongodb [root@MongoDB-server ~]# /etc/init.d/mongodb start MongoDB is running background... [root@MongoDB-server ~]# ps -ef|grep mongodb root 1687 1 12 23:58 pts/0 00:00:00 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf --auth root 1713 16606 0 23:58 pts/0 00:00:00 grep mongodb [root@MongoDB-server ~]# lsof -i:27017 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mongod 25342 root 6u IPv4 4330699 0t0 TCP *:27017 (LISTEN) 验证安全认证: [root@MongoDB-server ~]# mongo 127.0.0.1:27017 MongoDB shell version: 3.2.17-34-g4c1bae566c connecting to: 127.0.0.1:27017/test > use admin; switched to db admin > show dbs 2018-09-21T10:11:46.582+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok" : 0, "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }", "code" : 13 } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1 shellHelper.show@src/mongo/shell/utils.js:781:19 shellHelper@src/mongo/shell/utils.js:671:15 @(shellhelp2):1:1 > 如上由于没有认证,所以查看不到。需要认证后再次查看才可以。需要注意:认证时括号里面的用户名和密码用双引号,否则可能会认证失败!! > db.auth("admin","1234!@#$qwer"); 1 > show dbs admin 0.000GB local 0.000GB > 普通用户认证也是一样 > use grace; switched to db grace > db.stats(); { "ok" : 0, "errmsg" : "not authorized on admin to execute command { serverStatus: 1.0 }", "code" : 13 } > db.auth("grace","grace@1986"); 1 > db.stats(); { "db" : "grace", "collections" : 0, "objects" : 0, "avgObjSize" : 0, "dataSize" : 0, "storageSize" : 0, "numExtents" : 0, "indexes" : 0, "indexSize" : 0, "fileSize" : 0, "ok" : 1 } > 以上就表明了该mongodb启用了认证功能,并且认证成功了!