开启认证的复制集

1. 准备软件:
root@ubuntu:/disklvm/svr# ls
mongodb-linux-x86_64-ubuntu1404-3.2.12.tgz
root@ubuntu:/disklvm/svr# tar -xzvf mongodb-linux-x86_64-ubuntu1404-3.2.12.tgz 
mongodb-linux-x86_64-ubuntu1404-3.2.12/README
mongodb-linux-x86_64-ubuntu1404-3.2.12/THIRD-PARTY-NOTICES
mongodb-linux-x86_64-ubuntu1404-3.2.12/MPL-2
mongodb-linux-x86_64-ubuntu1404-3.2.12/GNU-AGPL-3.0
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongodump
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongorestore
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongoexport
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongoimport
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongostat
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongotop
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/bsondump
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongofiles
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongooplog
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongoperf
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongosniff
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongod
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongos
mongodb-linux-x86_64-ubuntu1404-3.2.12/bin/mongo
root@ubuntu:/disklvm/svr# mv mongodb-linux-x86_64-ubuntu1404-3.2.12 mongo3.2

2. 规划数据文件目录:

root@ubuntu:/disklvm/svr# mkdir -p /disklvm/conf/5000
root@ubuntu:/disklvm/svr# mkdir -p /disklvm/conf/5010
root@ubuntu:/disklvm/svr# mkdir -p /disklvm/conf/5020
root@ubuntu:/disklvm/svr# mkdir -p /disklvm/dbdata/5000
root@ubuntu:/disklvm/svr# mkdir -p /disklvm/dbdata/5010
root@ubuntu:/disklvm/svr# mkdir -p /disklvm/dbdata/5020

3. 准备参数文件:

vi /disklvm/conf/5000/mongo_5000.cnf
storage:
   dbPath: /disklvm/dbdata/5000   
   journal:
      enabled: true
   directoryPerDB: true
   engine: wiredTiger     
   wiredTiger:
      engineConfig: 
         directoryForIndexes: true
systemLog:
   destination: file
   path: /disklvm/dbdata/5000/mongod.log   
   logAppend: true
   quiet: true
processManagement:
   fork: true
   pidFilePath: /disklvm/dbdata/5000/mongod.pid  
operationProfiling:
   slowOpThresholdMs: 10
#replication:
#   oplogSizeMB: 50   
#   replSetName: pktest   
net:
   port: 5000

这里先启动一个无认证无复制集的实例。

root@ubuntu:/disklvm/svr# /disklvm/svr/mongo3.2/bin/mongod -f /disklvm/conf/5000/mongo_5000.cnf 
about to fork child process, waiting until server is ready for connections.
forked process: 1506
child process started successfully, parent exiting

4. 进入数据库,创建认证账户:

use admin;
db.createUser( {
 user: "dbdmin",
 pwd: "ZktMM0AhZljXg",
 roles: [ { role: "root", db: "admin" } ]
 });

5. 创建KEYFILE:

root@ubuntu:/disklvm/svr# openssl rand -base64 741 > /disklvm/conf/5000/mongo5000_key
root@ubuntu:/disklvm/svr# chmod 600 /disklvm/conf/5000/mongo5000_key

6. 关闭数据库:

> use admin;
switched to db admin
> db.shutdownServer()

7. 修改参数文件:

root@ubuntu:/disklvm/svr# cat /disklvm/conf/5000/mongo_5000.cnf 
storage:
   dbPath: /disklvm/dbdata/5000   
   journal:
      enabled: true
   directoryPerDB: true
   engine: wiredTiger     
   wiredTiger:
      engineConfig: 
         directoryForIndexes: true
systemLog:
   destination: file
   path: /disklvm/dbdata/5000/mongod.log   
   logAppend: true
   quiet: true
processManagement:
   fork: true
   pidFilePath: /disklvm/dbdata/5000/mongod.pid  
operationProfiling:
   slowOpThresholdMs: 10
replication:
   oplogSizeMB: 50   
   replSetName: pktest   
net:
   port: 5000 
security:
   authorization: enabled
   keyFile: /disklvm/conf/5000/mongo5000_key
 

8. 准备从库实例的参数文件和KEYFILE:

root@ubuntu:/disklvm/svr# cp /disklvm/conf/5000/mongo5000_key /disklvm/conf/5010/mongo5010_key
root@ubuntu:/disklvm/svr# cp /disklvm/conf/5000/mongo5000_key /disklvm/conf/5020/mongo5020_key
root@ubuntu:/disklvm/svr# cp /disklvm/conf/5000/mongo_5000.cnf /disklvm/conf/5010/mongo_5010.cnf
root@ubuntu:/disklvm/svr# cp /disklvm/conf/5000/mongo_5000.cnf /disklvm/conf/5020/mongo_5020.cnf
root@ubuntu:/disklvm/svr# sed -i 's/5000/5010/g' /disklvm/conf/5010/mongo_5010.cnf
root@ubuntu:/disklvm/svr# sed -i 's/5000/5020/g' /disklvm/conf/5020/mongo_5020.cnf
 
 

9. 启动所有实例:

root@ubuntu:/disklvm/svr# /disklvm/svr/mongo3.2/bin/mongod -f /disklvm/conf/5000/mongo_5000.cnf 
about to fork child process, waiting until server is ready for connections.
forked process: 2084
child process started successfully, parent exiting
root@ubuntu:/disklvm/svr# /disklvm/svr/mongo3.2/bin/mongod -f /disklvm/conf/5010/mongo_5010.cnf 
about to fork child process, waiting until server is ready for connections.
forked process: 2108
child process started successfully, parent exiting
root@ubuntu:/disklvm/svr# /disklvm/svr/mongo3.2/bin/mongod -f /disklvm/conf/5020/mongo_5020.cnf 
about to fork child process, waiting until server is ready for connections.
forked process: 2131
child process started successfully, parent exiting

10. 新建复制集,  并初始化:

root@ubuntu:/disklvm/svr# /disklvm/svr/mongo3.2/bin/mongo 127.0.0.1:5000/admin -u dbdmin -p ZktMM0AhZljXg
MongoDB shell version: 3.2.12
connecting to: 127.0.0.1:5000/admin
Server has startup warnings: 
2017-05-12T09:38:01.008+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2017-05-12T09:38:01.009+0800 I CONTROL  [initandlisten] 
> config={_id:"pktest",members:[{_id:0, host:"192.168.137.3:5000"},{_id:1, host:"192.168.137.3:5010"},{_id:2, host:"192.168.137.3:5020",hidden:true, priority:0}]}
{
    "_id" : "pktest",
    "members" : [
        {
            "_id" : 0,
            "host" : "192.168.137.3:5000"
        },
        {
            "_id" : 1,
            "host" : "192.168.137.3:5010"
        },
        {
            "_id" : 2,
            "host" : "192.168.137.3:5020",
            "hidden" : true,
            "priority" : 0
        }
    ]
}
> rs.initiate(config)
{ "ok" : 1 }
查看复制状态:
pktest:PRIMARY> rs.status()
{
    "set" : "pktest",
    "date" : ISODate("2017-05-12T01:45:44.176Z"),
    "myState" : 1,
    "term" : NumberLong(1),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "members" : [
        {
            "_id" : 0,
            "name" : "192.168.137.3:5000",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 466,
            "optime" : {
                "ts" : Timestamp(1494553495, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2017-05-12T01:44:55Z"),
            "infoMessage" : "could not find member to sync from",
            "electionTime" : Timestamp(1494553494, 1),
            "electionDate" : ISODate("2017-05-12T01:44:54Z"),
            "configVersion" : 1,
            "self" : true
        },
        {
            "_id" : 1,
            "name" : "192.168.137.3:5010",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 59,
            "optime" : {
                "ts" : Timestamp(1494553495, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2017-05-12T01:44:55Z"),
            "lastHeartbeat" : ISODate("2017-05-12T01:45:42.681Z"),
            "lastHeartbeatRecv" : ISODate("2017-05-12T01:45:43.409Z"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "192.168.137.3:5000",
            "configVersion" : 1
        },
        {
            "_id" : 2,
            "name" : "192.168.137.3:5020",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 59,
            "optime" : {
                "ts" : Timestamp(1494553495, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2017-05-12T01:44:55Z"),
            "lastHeartbeat" : ISODate("2017-05-12T01:45:42.661Z"),
            "lastHeartbeatRecv" : ISODate("2017-05-12T01:45:43.403Z"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "192.168.137.3:5000",
            "configVersion" : 1
        }
    ],
    "ok" : 1
}
 
 

验证数据同步:

pktest:PRIMARY> use test;
switched to db test
pktest:PRIMARY> for(i=0;i<20;i++){db.scores.save({student:i,score:20})};
WriteResult({ "nInserted" : 1 })

从库查看:

root@ubuntu:~# /disklvm/svr/mongo3.2/bin/mongo 127.0.0.1:5010
MongoDB shell version: 3.2.12
connecting to: 127.0.0.1:5010/test
pktest:SECONDARY> use test;
switched to db test
pktest:SECONDARY> db.scores.find()
Error: error: {
    "ok" : 0,
    "errmsg" : "not authorized on test to execute command { find: \"scores\", filter: {} }",
    "code" : 13
}

pktest:SECONDARY> 

这里的登录是没有经过认证的, 发现无法查看数据。

root@ubuntu:~# /disklvm/svr/mongo3.2/bin/mongo 127.0.0.1:5010/admin -u dbdmin -p ZktMM0AhZljXg
MongoDB shell version: 3.2.12
connecting to: 127.0.0.1:5010/admin
Server has startup warnings: 
2017-05-12T09:38:09.047+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2017-05-12T09:38:09.047+0800 I CONTROL  [initandlisten] 
pktest:SECONDARY> rs.slaveOk()
pktest:SECONDARY> use test;
switched to db test
pktest:SECONDARY> db.scores.count()

11. 内置用户角色说明:

数据库用户角色: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数据库中可用。超级账号,超级权限
12 创建用户测试:
12.1 创建一个针对所有库可读的用户:
pktest:PRIMARY> db.createUser({user:"hxg", pwd:"123456", roles:[{role:"readAnyDatabase", db:"admin"}]})
Successfully added user: {
    "user" : "hxg",
    "roles" : [
        {
            "role" : "readAnyDatabase",
            "db" : "admin"
        }
    ]
}
pktest:PRIMARY> use admin;
switched to db admin
pktest:PRIMARY> db.auth("hxg","123456")
1
pktest:PRIMARY> use a;
switched to db a
pktest:PRIMARY> db.t.find()
{ "_id" : ObjectId("5919089b241ebf2f04dc87c0"), "name" : "a" }
pktest:PRIMARY> use b;
switched to db b
pktest:PRIMARY> db.tb.find()
{ "_id" : ObjectId("591908ae241ebf2f04dc87c1"), "name" : "a" }
pktest:PRIMARY> 
pktest:PRIMARY> db.tb.save({"name":"a"})
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on b to execute command { insert: \"tb\", documents: [ { name: \"a\", _id: ObjectId('5919097c241ebf2f04dc87c2') } ], ordered: true }"
    }
})

12.2. 创建一个对某一个库有读写权限:

pktest:PRIMARY> db.createUser({user:"hxg3", pwd:"123456", roles:[{role:"readWrite",db:"hxg3"}]})
Successfully added user: {
    "user" : "hxg3",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "hxg3"
        }
    ]
}
pktest:PRIMARY> use hxg3;
switched to db hxg3
pktest:PRIMARY> db.auth("hxg3","123456")
Error: Authentication failed.   #用户登录必须在创建用户时所使用的DB下进行登录, 否则会登录失败
0
pktest:PRIMARY> use admin;
switched to db admin
pktest:PRIMARY> db.auth("hxg3","123456")
1
pktest:PRIMARY> use hxg3;
switched to db hxg3
pktest:PRIMARY> db.t3.save({"name":"c"});
WriteResult({ "nInserted" : 1 })
pktest:PRIMARY> db.t3.find();
{ "_id" : ObjectId("59190afe241ebf2f04dc87c3"), "name" : "c" }
pktest:PRIMARY> 
pktest:PRIMARY> use t;
switched to db t
pktest:PRIMARY> show tables;
2017-05-15T09:59:28.548+0800 E QUERY    [thread1] Error: listCollections failed: {
    "ok" : 0,
    "errmsg" : "not authorized on t to execute command { listCollections: 1.0, filter: {} }",
    "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16
shellHelper.show@src/mongo/shell/utils.js:754:9
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1

  


 
 

转载于:https://www.cnblogs.com/o-to-s/articles/7928964.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值