- 默認(rèn)情況下,MongoDB實(shí)例啟動(dòng)運(yùn)行時(shí)是沒(méi)有啟用用戶(hù)訪問(wèn)權(quán)限控制的,也就是說(shuō),在實(shí)例本機(jī)服務(wù)器上都可以隨意連接到實(shí)例進(jìn)行各種操作,MongoDB不會(huì)對(duì)連接客戶(hù)端進(jìn)行用戶(hù)驗(yàn)證,這是非常危險(xiǎn)的。
- mongodb官網(wǎng)上說(shuō),為了能保障mongodb的安全可以做以下幾個(gè)步驟:
- 使用新的端口,默認(rèn)的27017端口,一旦知道了ip就能連接上,不太安全。
- 設(shè)置mongodb的網(wǎng)絡(luò)環(huán)境,最好將mongodb部署到公司服務(wù)器內(nèi)網(wǎng),這樣外網(wǎng)是訪問(wèn)不到的,公司內(nèi)部訪問(wèn)使用代理工具等。
- 開(kāi)啟安全認(rèn)證,既要設(shè)置服務(wù)器之間的內(nèi)部認(rèn)證方式,又要設(shè)置客戶(hù)端連接到集群的賬號(hào)密碼認(rèn)證方式。
- 為了強(qiáng)制開(kāi)啟用戶(hù)訪問(wèn)控制(用戶(hù)驗(yàn)證),需要在MongoDB實(shí)例啟動(dòng)時(shí)使用選項(xiàng)
--auth或在指定啟動(dòng)的配置文件中添加選項(xiàng)auth=true。 -
訪問(wèn)控制:MongoDB使用的是基于角色的訪問(wèn)控制(Role-Based Access Control,RBAC)來(lái)管理用戶(hù)對(duì)實(shí)例的訪問(wèn)。通過(guò)對(duì)用戶(hù)授予一個(gè)或多個(gè)角色來(lái)控制用戶(hù)訪問(wèn)數(shù)據(jù)庫(kù)資源的權(quán)限和數(shù)據(jù)庫(kù)操作的權(quán)限,在對(duì)用戶(hù)分配角色之前,用戶(hù)無(wú)法訪問(wèn)實(shí)例。 -
角色:在MongoDB中通過(guò)角色對(duì)用戶(hù)授予相應(yīng)數(shù)據(jù)庫(kù)資源的操作權(quán)限,每個(gè)角色當(dāng)中的權(quán)限可以顯式指定,也可以通過(guò)繼承其它角色的權(quán)限,或者兩者都存在的權(quán)限。 -
權(quán)限:由指定的數(shù)據(jù)庫(kù)資源(resource)以及允許在指定資源上進(jìn)行的操作(action)組成。- 資源(resource)包括:數(shù)據(jù)庫(kù)、集合、部分集合和集群;
- 操作(action)包括:對(duì)資源進(jìn)行的增、刪、改、查(CRUD)操作。
- 在角色定義時(shí)可以包含一個(gè)或多個(gè)已存在的角色,新創(chuàng)建的角色會(huì)繼承包含的角色中所有的權(quán)限。在同一個(gè)數(shù)據(jù)庫(kù)中,新創(chuàng)建角色可以繼承其它角色的權(quán)限,在 admin 數(shù)據(jù)庫(kù)中創(chuàng)建的角色可以繼承在其它任意數(shù)據(jù)庫(kù)中角色的權(quán)限。
- 常用的內(nèi)置角色擁有的權(quán)限:
- 數(shù)據(jù)庫(kù)用戶(hù)角色:
read、readWrite; - 所有數(shù)據(jù)庫(kù)用戶(hù)角色:
readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase; - 數(shù)據(jù)庫(kù)管理角色:
dbAdmin、dbOwner、userAdmin; - 集群管理角色:
clusterAdmin、clusterManager、clusterMonitor
hostManager; - 備份恢復(fù)角色:
backup、restore; - 超級(jí)用戶(hù)角色:
root; - 內(nèi)部角色:
system。
- 數(shù)據(jù)庫(kù)用戶(hù)角色:
| 權(quán)限 | 描述 |
|---|---|
| read | 讀取指定數(shù)據(jù)庫(kù)中的任何數(shù)據(jù) |
| readWrite | 讀寫(xiě)指定數(shù)據(jù)庫(kù)中的任何數(shù)據(jù),包括創(chuàng)建、重命名、刪除集合 |
| readAnyDatabase | 讀取所有數(shù)據(jù)庫(kù)中的任何數(shù)據(jù)(除了數(shù)據(jù)庫(kù)config和local之外) |
| readWriteAnyDatabase | 讀寫(xiě)所有數(shù)據(jù)庫(kù)中的任何數(shù)據(jù)(除了數(shù)據(jù)庫(kù)config和local之外) |
| userAdminAnyDatabase | 在指定數(shù)據(jù)庫(kù)創(chuàng)建和修改用戶(hù)(除了數(shù)據(jù)庫(kù)config和local之外) |
| dbAdminAnyDatabase | 讀取任何數(shù)據(jù)庫(kù)以及對(duì)數(shù)據(jù)庫(kù)進(jìn)行清理、修改、壓縮、獲取統(tǒng)計(jì)信息、執(zhí)行檢查等操作(除了數(shù)據(jù)庫(kù)config和local之外) |
| dbAdmin | 讀取指定數(shù)據(jù)庫(kù)以及對(duì)數(shù)據(jù)庫(kù)進(jìn)行清理、修改、壓縮、獲取統(tǒng)計(jì)信息、執(zhí)行檢查等操作 |
| userAdmin | 在指定數(shù)據(jù)庫(kù)創(chuàng)建和修改用戶(hù) |
| clusterAdmin | 對(duì)整個(gè)集群或數(shù)據(jù)庫(kù)系統(tǒng)進(jìn)行管理操作 |
| backup | 備份MongoDB數(shù)據(jù)最小的權(quán)限 |
| restore | 從備份文件中還原恢復(fù)MongoDB數(shù)據(jù)(除了system.profile集合)的權(quán)限 |
| root | 超級(jí)賬號(hào),超級(jí)權(quán)限 |
- 對(duì)單實(shí)例(未開(kāi)啟副本集或分片)的MongoDB服務(wù)開(kāi)啟安全認(rèn)證:
- 按照普通無(wú)授權(quán)認(rèn)證的配置來(lái)編寫(xiě)服務(wù)端的配置文件:
vim /opt/mongodb/conf/mongod.conf:
systemLog:
destination: file
path: /opt/mongodb/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27017
- 按之前未開(kāi)啟認(rèn)證的方式(不添加
--auth參數(shù))來(lái)啟動(dòng)MongoDB服務(wù):
[root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 32072
child process started successfully, parent exiting
- 提示:在操作用戶(hù)和啟動(dòng)mongod服務(wù)時(shí)盡量不要開(kāi)啟授權(quán)。
- 登錄Mongo客戶(hù)端:
/opt/mongodb/bin/mongo --port 27017 - 創(chuàng)建兩個(gè)管理員用戶(hù),一個(gè)是系統(tǒng)的超級(jí)管理員
myroot,一個(gè)是admin庫(kù)的管理用戶(hù)myadmin:
> use admin
switched to db admin
> db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
> db.createUser({user:"myadmin",pwd:"123456",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Successfully added user: {
"user" : "myadmin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
> db.system.users.find() #查看已創(chuàng)建了的用戶(hù)的情況
{ "_id" : "admin.myroot", "userId" : UUID("9c2dec75-971f-4407-9211-f03498a904fe"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "zxV1hyvdbmi5RGwgx6lQHA==", "storedKey" : "WRCCuZl3jHCQo9z3nv0f028PJYs=", "serverKey" : "iX9+9kAcKfcmQjeyK2QxSKmEzvo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "VBbrTSvxUWq+VS6qAeBWa7Vc+nMQ8IOCfkNmfg==", "storedKey" : "7yV5V/kF8ToxM6OOJVH4jFpUjsW6t1NHXwWBoEjLDxw=", "serverKey" : "+PP4GPcJ83SOd6O/CuxjqbRf2VMv4u+2yHAQf/gyjVE=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "admin.myadmin", "userId" : UUID("a7f5b9e9-cbb1-48c3-9020-cc83261ffe4d"), "user" : "myadmin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "cSj5KAMm1cAD1YCQExTACg==", "storedKey" : "lh1ElhvOjc6dYu5yE0TWwM4POuI=", "serverKey" : "KzAg75OGyopuH2WjSFE43Lv0UXI=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "e8tcrQJcp2/+jdHI0p8oVT1gXrKlr3yLUKo65g==", "storedKey" : "b6c8RklClG8U2DXKsWJ9p6tdElhDesw/I6OyMk3alFk=", "serverKey" : "jlD+pal4tYh89vBJkgXc4i932xNv7TrIOsulyRzgOyU=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
> db.dropUser("myadmin") #刪除用戶(hù)
true
> db.system.users.find()
{ "_id" : "admin.myroot", "userId" : UUID("9c2dec75-971f-4407-9211-f03498a904fe"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "zxV1hyvdbmi5RGwgx6lQHA==", "storedKey" : "WRCCuZl3jHCQo9z3nv0f028PJYs=", "serverKey" : "iX9+9kAcKfcmQjeyK2QxSKmEzvo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "VBbrTSvxUWq+VS6qAeBWa7Vc+nMQ8IOCfkNmfg==", "storedKey" : "7yV5V/kF8ToxM6OOJVH4jFpUjsW6t1NHXwWBoEjLDxw=", "serverKey" : "+PP4GPcJ83SOd6O/CuxjqbRf2VMv4u+2yHAQf/gyjVE=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
> db.changeUserPassword("myroot", "123456") #修改密碼
- Mongodb中所有的用戶(hù)信息都保存在admin數(shù)據(jù)庫(kù)的集合
system.users中,其保存用戶(hù)名、密碼和數(shù)據(jù)庫(kù)信息。若不指定數(shù)據(jù)庫(kù),則創(chuàng)建指定權(quán)限的用戶(hù)在所有數(shù)據(jù)庫(kù)上都有效,如:{role:"userAdminAnyDatabase", db:""}。 - 測(cè)試添加的用戶(hù)是否正確:
> db.auth("myroot","12345")
Error: Authentication failed.
0
> db.auth("myroot","123456")
1
- 創(chuàng)建普通用戶(hù)既可以在沒(méi)有開(kāi)啟認(rèn)證時(shí)添加,也可以在開(kāi)啟認(rèn)證之后添加,但開(kāi)啟認(rèn)證之后,必須使用有操作admin庫(kù)的用戶(hù)登錄認(rèn)證后才能操作。
> use articledb
switched to db articledb
> db.createUser({user: "bobo", pwd: "123456", roles: [{ role: "readWrite", db:"articledb" }]})
Successfully added user: {
"user" : "bobo",
"roles" : [
{
"role" : "readWrite",
"db" : "articledb"
}
]
}
> db.auth("bobo","123456")
1
- 若開(kāi)啟認(rèn)證后,則登錄客戶(hù)端的用戶(hù)必須使用admin庫(kù)的角色。如:擁有root角色的myadmin用戶(hù),再通過(guò)myadmin用戶(hù)去創(chuàng)建其它角色的用戶(hù)。
- 關(guān)閉已啟動(dòng)的mongod服務(wù),然后開(kāi)啟服務(wù)端認(rèn)證:①在啟動(dòng)時(shí)指定參數(shù)
-- auth:/opt/mongodb/bin/mongod -f /opt/mongodb/conf/mongod.conf --auth;②修改服務(wù)器配置文件:vim /opt/mongodb/conf/mongod.conf;③啟動(dòng)時(shí)不用加--auth參數(shù):/opt/mongodb/bin/mongod -f /opt/mongodb/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27017
security:
authorization: enabled
- 開(kāi)啟認(rèn)證后使用mongo登錄客戶(hù)端:
/opt/mongodb/bin/mongo --port 27017,執(zhí)行該命令后發(fā)現(xiàn)打印的日志比較少了,原因:需要認(rèn)證才可以進(jìn)行下一步操作。
> show dbs
> use admin
switched to db admin
> show collections
Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus
> db.system.users.find()
Error: error: {
"ok" : 0,
"errmsg" : "command find requires authentication",
"code" : 13,
"codeName" : "Unauthorized"
}
> db.auth("myroot","123456")
1
> db.system.users.find()
{ "_id" : "admin.myroot", "userId" : UUID("9c2dec75-971f-4407-9211-f03498a904fe"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "X2ugoiTtTxXo0y2VxUo70A==", "storedKey" : "CHV7inualEXuXcLLCKH/dCAeKhM=", "serverKey" : "AukG2aEGIeaoKCFwniaGGRJyP/A=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "qbd7wbnOdGq/cgF+rbpq9quQMM/mHzlLKkzGew==", "storedKey" : "1rHvt+DM5kAnAMvkD9KgIH/2YLxGLES32tg/rP0qpvI=", "serverKey" : "g1H4a9s+l6HQ6wUAsTWxsxBQZJWD3R2PmRjFGnHzsMo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "articledb.bobo", "userId" : UUID("adad58df-b490-4f6e-9880-b85fd93d9778"), "user" : "bobo", "db" : "articledb", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "30mHAIGa3uG1nnbIrRAZgw==", "storedKey" : "HVfm1OKF4D4xZg+kDLNJiJOmxKo=", "serverKey" : "cqSEGV6NmADDcV8QhrTsz6zs8Nw=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "3UOrivatwuZk6jOXHMhmkIBzBDJfgoQh3umb8g==", "storedKey" : "Ad7s/dnsU9+bUNSBmkacO6Ct1fd+UPOfObnvTz+9o1E=", "serverKey" : "9msoX57PpWsK9hz8zOfEXD1U6mCX1Q79WufThQgSmck=" } }, "roles" : [ { "role" : "readWrite", "db" : "articledb" } ] }
> show collections
system.users
system.version
> exit
bye
--------------------------------------------------------------------------------------
> use articledb
switched to db articledb
> db.auth("bobo","123456")
1
> show collections
comment
> show dbs
articledb 0.000Gb

使用Compass來(lái)認(rèn)證登錄
- 在登錄客戶(hù)端時(shí)直接認(rèn)證:
/opt/mongodb/bin/mongo --port 27017 --authenticationDatabase admin -u myroot -p 123456或者/opt/mongodb/bin/mongo --port 27017 --authenticationDatabase articledb -u bobo -p 123456,其中-u:用戶(hù)名;-p:密碼;--authenticationDatabase:指定連接到哪個(gè)數(shù)據(jù)庫(kù)。當(dāng)?shù)卿浭侵付ㄓ脩?hù)名和密碼時(shí),必須指定對(duì)應(yīng)的數(shù)據(jù)庫(kù)! - 對(duì)副本集執(zhí)行訪問(wèn)控制需要配置兩個(gè)方面:
- 副本集和共享集群的各個(gè)節(jié)點(diǎn)之間使用內(nèi)部身份驗(yàn)證,可以使用密鑰文件或
x.509證書(shū)。密鑰文件比較簡(jiǎn)單,本文使用密鑰文件,若是測(cè)試環(huán)境官方則推薦使用密鑰文件;若是正式環(huán)境,官方則推薦x.509證書(shū)。原理:集群中每一個(gè)實(shí)例彼此連接時(shí)都檢驗(yàn)彼此使用的證書(shū)內(nèi)容是否相同。只有證書(shū)相同的實(shí)例彼此才可以互相訪問(wèn)。 - 對(duì)于集群外部的訪問(wèn),使用客戶(hù)端連接到mongodb集群時(shí),需要開(kāi)啟訪問(wèn)授權(quán)。
- 副本集和共享集群的各個(gè)節(jié)點(diǎn)之間使用內(nèi)部身份驗(yàn)證,可以使用密鑰文件或
- 副本集的每個(gè)mongod實(shí)例都使用keyfile的內(nèi)容作為共享密碼,只有具有正確密鑰文件的mongod或者mongos實(shí)例才可以連接到副本集。密鑰文件的內(nèi)容必須在6到1024個(gè)字符之間,且在unix/linux系統(tǒng)中文件所有者必須有對(duì)文件至少有讀的權(quán)限。
- 啟動(dòng)副本集服務(wù):
[root@dev mongodb]# ps -ef | grep mongod
root 32285 31928 0 16:52 pts/0 00:00:00 grep --color=auto mongod
[root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 32288
child process started successfully, parent exiting
[root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 32367
child process started successfully, parent exiting
[root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 32449
child process started successfully, parent exiting
- 登錄主節(jié)點(diǎn)并創(chuàng)建一個(gè)管理員賬戶(hù):
[root@dev mongodb]# /opt/mongodb/bin/mongo --port 27018
myrs:PRIMARY> use admin
switched to db admin
myrs:PRIMARY> db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
- 創(chuàng)建副本集認(rèn)證的key文件:使用openssl生成密碼文件,然后使用chmod來(lái)更改文件權(quán)限,僅為文件所有者提供只讀權(quán)限:
[root@dev ~]# openssl rand -base64 90 -out ./mongo.keyfile
[root@dev ~]# ll ./mongo.keyfile
-rw-r--r-- 1 root root 122 Jan 13 17:03 mongo.keyfile
[root@dev ~]# chmod 400 ./mongo.keyfile
[root@dev ~]# ll ./mongo.keyfile
-r-------- 1 root root 122 Jan 13 17:03 mongo.keyfile
- 注意:副本集中每個(gè)節(jié)點(diǎn)都必須使用同一份keyfile,一般是在一臺(tái)機(jī)器上生成,然后拷貝到其它機(jī)器上,且必須有只讀權(quán)限。
[root@dev ~]# cp ./mongo.keyfile /opt/mongodb/replica_sets/myrs_27017/conf
[root@dev ~]# cp ./mongo.keyfile /opt/mongodb/replica_sets/myrs_27018/conf
[root@dev ~]# cp ./mongo.keyfile /opt/mongodb/replica_sets/myrs_27019/conf
[root@dev ~]# ll /opt/mongodb/replica_sets/myrs_27018/conf
total 8
-rw-r--r-- 1 root root 418 Jan 11 16:57 mongod.conf
-r-------- 1 root root 122 Jan 13 17:08 mongo.keyfile
- 修改副本集中各個(gè)節(jié)點(diǎn)的配置文件(指定keyfile的位置和開(kāi)啟安全認(rèn)證):
vim /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/replica_sets/myrs_27017/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/replica_sets/myrs_27017/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/replica_sets/myrs_27017/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27017
replication:
replSetName: myrs
security:
keyFile: /opt/mongodb/replica_sets/myrs_27017/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/replica_sets/myrs_27018/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/replica_sets/myrs_27018/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/replica_sets/myrs_27018/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27018
replication:
replSetName: myrs
security:
keyFile: /opt/mongodb/replica_sets/myrs_27018/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/replica_sets/myrs_27019/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/replica_sets/myrs_27019/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/replica_sets/myrs_27019/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27019
replication:
replSetName: myrs
security:
keyFile: /opt/mongodb/replica_sets/myrs_27019/conf/mongo.keyfile
authorization: enabled
- 先關(guān)閉副本集進(jìn)程號(hào):
kill -2 副本集中各個(gè)節(jié)點(diǎn)的進(jìn)程號(hào),再分別啟動(dòng)副本集節(jié)點(diǎn):
[root@dev ~]# ps -ef | grep mongod
root 32616 31928 0 17:17 pts/0 00:00:00 grep --color=auto mongod
[root@dev ~]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 32619
child process started successfully, parent exiting
[root@dev ~]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 32714
child process started successfully, parent exiting
[root@dev ~]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
about to fork child process, waiting until server is ready for connections.
forked process: 341
child process started successfully, parent exiting
[root@dev ~]# ps -ef | grep mongod
root 341 1 2 17:18 ? 00:00:01 /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
root 415 31928 0 17:19 pts/0 00:00:00 grep --color=auto mongod
root 32619 1 2 17:18 ? 00:00:01 /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
root 32714 1 2 17:18 ? 00:00:01 /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
- 登錄主節(jié)點(diǎn)客戶(hù)端并添加一個(gè)普通賬號(hào):
[root@dev ~]# /opt/mongodb/bin/mongo --port 27017
myrs:PRIMARY> show dbs
myrs:PRIMARY> use admin
switched to db admin
myrs:PRIMARY> db.auth("myroot","123456")
1
myrs:PRIMARY> show dbs
admin 0.000GB
articledb 0.000GB
config 0.000GB
local 0.001GB
myrs:PRIMARY> use articledb
switched to db articledb
myrs:PRIMARY> db.createUser({user: "bobo", pwd: "123456", roles: ["readWrite"]})
Successfully added user: { "user" : "bobo", "roles" : [ "readWrite" ] }
- 分片集群環(huán)境下的安全認(rèn)證和副本集環(huán)境下基本上一樣,但分片集群的服務(wù)器環(huán)境和架構(gòu)較為復(fù)雜,建議在搭建分片集群時(shí),直接加入安全認(rèn)證和服務(wù)器間的鑒權(quán),若之前有數(shù)據(jù),則先將之前的數(shù)據(jù)備份出來(lái),再還原回去。
- 依次kill mongos路由、配置副本集服務(wù),分片副本集服務(wù),主從節(jié)點(diǎn)直到所有成員都離線為止。在kill副本集時(shí),建議先kill仲裁者,再kill副本節(jié)點(diǎn),最后是主節(jié)點(diǎn),以避免潛在的回滾。kill完要檢查一下,避免有的沒(méi)有被kill。
- 創(chuàng)建副本集認(rèn)證的key文件:使用openssl生成密碼文件,然后使用chmod來(lái)更改文件權(quán)限,僅為文件所有者提供只讀權(quán)限:
[root@dev ~]# openssl rand -base64 90 -out ./mongo.keyfile
[root@dev ~]# ll ./mongo.keyfile
-rw-r--r-- 1 root root 122 Jan 13 17:03 mongo.keyfile
[root@dev ~]# chmod 400 ./mongo.keyfile
[root@dev ~]# ll ./mongo.keyfile
-r-------- 1 root root 122 Jan 13 17:03 mongo.keyfile
- 注意:副本集中每個(gè)節(jié)點(diǎn)都必須使用同一份keyfile,一般是在一臺(tái)機(jī)器上生成,然后拷貝到其它機(jī)器上,且必須有只讀權(quán)限。
[root@dev ~]# echo '/opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongo.keyfile
> /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile' | xargs -n 1 cp -v /root/mongo.keyfile
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/mymongos_27017/conf/mongo.keyfile’
‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile’
- 修改副本集中各個(gè)節(jié)點(diǎn)的配置文件(指定keyfile的位置和開(kāi)啟安全認(rèn)證):
vim /opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myshardrs01_27018/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myshardrs01_27018/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myshardrs01_27018/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27018
replication:
replSetName: myshardrs01
sharding:
clusterRole: shardsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myshardrs01_27118/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myshardrs01_27118/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myshardrs01_27118/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27118
replication:
replSetName: myshardrs01
sharding:
clusterRole: shardsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myshardrs01_27218/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myshardrs01_27218/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myshardrs01_27218/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27218
replication:
replSetName: myshardrs01
sharding:
clusterRole: shardsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myshardrs02_27318/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myshardrs02_27318/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myshardrs02_27318/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27318
replication:
replSetName: myshardrs02
sharding:
clusterRole: shardsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myshardrs02_27418/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myshardrs02_27418/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myshardrs02_27418/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27418
replication:
replSetName: myshardrs02
sharding:
clusterRole: shardsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myshardrs02_27518/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myshardrs02_27518/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myshardrs02_27518/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27518
replication:
replSetName: myshardrs02
sharding:
clusterRole: shardsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myconfigrs_27019/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myconfigrs_27019/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myconfigrs_27019/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27019
replication:
replSetName: myconfigrs
sharding:
clusterRole: configsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myconfigrs_27119/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myconfigrs_27119/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myconfigrs_27119/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27119
replication:
replSetName: myconfigrs
sharding:
clusterRole: configsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongod.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/myconfigrs_27219/logs/mongod.log
logAppend: true
storage:
dbPath: /opt/mongodb/sharded_cluster/myconfigrs_27219/data/db
journal:
enabled: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/myconfigrs_27219/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27219
replication:
replSetName: myconfigrs
sharding:
clusterRole: configsvr
security:
keyFile: /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongo.keyfile
authorization: enabled
vim /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongos.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/mymongos_27017/logs/mongod.log
logAppend: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/mymongos_27017/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27017
sharding:
configDB: myconfigrs/公網(wǎng)ip:27019,公網(wǎng)ip:27119,公網(wǎng)ip:27219
security:
keyFile: /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongo.keyfile
vim /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongos.conf
systemLog:
destination: file
path: /opt/mongodb/sharded_cluster/mymongos_27117/logs/mongod.log
logAppend: true
processManagement:
fork: true
pidFilePath: /opt/mongodb/sharded_cluster/mymongos_27117/logs/mongod.pid
net:
bindIp: localhost,192.168.0.128
port: 27117
sharding:
configDB: myconfigrs/公網(wǎng)ip:27019,公網(wǎng)ip:27119,公網(wǎng)ip:27219
security:
keyFile: /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile
- mongos比mongod少了
authorization: enabled的配置,原因:副本集加分片的安全認(rèn)證需要配置兩方面的,副本集中各個(gè)節(jié)點(diǎn)之間使用內(nèi)部身份驗(yàn)證,用于內(nèi)部各個(gè)mongo實(shí)例的通信,只有相同keyfile才能相互訪問(wèn),所以都要開(kāi)啟keyFile: /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile。然而對(duì)于所有的mongod,才是真正保存數(shù)據(jù)的分片。mongos只做路由,不保存數(shù)據(jù)。所有的mongod開(kāi)啟訪問(wèn)數(shù)據(jù)的授權(quán)authorization: enabled,這樣只有用戶(hù)登錄的賬號(hào)密碼正確才能訪問(wèn)到數(shù)據(jù)。 - 必須依次啟動(dòng)配置節(jié)點(diǎn)、分片節(jié)點(diǎn)、路由節(jié)點(diǎn),注意啟動(dòng)順序:
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongod.conf
/opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongod.conf
/opt/mongodb/bin/mongos -f /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongos.conf
/opt/mongodb/bin/mongos -f /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongos.conf
- 通過(guò)localhost登錄任意一個(gè)mongos路由,并創(chuàng)建一個(gè)管理員帳號(hào)和一個(gè)普通權(quán)限的帳號(hào):
[root@dev mongodb]# /opt/mongodb/bin/mongo --port 27017
mongos> use admin
switched to db admin
mongos> db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
mongos> db.auth("myroot","123456")
1
mongos> db.createUser({user: "bobo", pwd: "123456", roles: [{ role: "readWrite",db: "articledb" }]})
Successfully added user: {
"user" : "bobo",
"roles" : [
{
"role" : "readWrite",
"db" : "articledb"
}
]
}
mongos> db.auth("bobo","123456")
1
- 提示:通過(guò)mongos添加的賬號(hào)信息,只會(huì)保存到配置節(jié)點(diǎn)的服務(wù)器中,具體的數(shù)據(jù)節(jié)點(diǎn)不保存賬號(hào)信息,所以分片中的賬號(hào)信息不涉及到同步問(wèn)題。
- 在mongo客戶(hù)端登錄mongos路由,用管理員帳號(hào)登錄可查看分片情況:
[root@dev mongodb]# /opt/mongodb/bin/mongo --port 27017
mongos> use admin
switched to db admin
mongos> db.auth("myroot","123456")
1
mongos> sh.status()
--- Sharding Status ---
sharding version: {
"_id" : 1,
"minCompatibleVersion" : 5,
"currentVersion" : 6,
"clusterId" : ObjectId("5ffd13a86c140163a85aa531")
}
shards:
{ "_id" : "myshardrs01", "host" : "myshardrs01/公網(wǎng)ip:27018,公網(wǎng)ip:27118", "state" : 1 }
{ "_id" : "myshardrs02", "host" : "myshardrs02/公網(wǎng)ip:27318,公網(wǎng)ip:27418", "state" : 1 }
active mongoses:
"4.4.3" : 2
autosplit:
Currently enabled: yes
balancer:
Currently enabled: yes
Currently running: no
Failed balancer rounds in last 5 attempts: 2
Last reported error: Could not find host matching read preference { mode: "primary" } for set myshardrs02
Time of Reported error: Wed Jan 13 2021 22:44:38 GMT+0800 (CST)
Migration Results for the last 24 hours:
No recent migrations
databases:
{ "_id" : "articledb", "primary" : "myshardrs02", "partitioned" : true, "version" : { "uuid" : UUID("03cc6699-146c-46f3-b266-5f43b8d65a39"), "lastMod" : 1 } }
articledb.author
shard key: { "age" : 1 }
unique: false
balancing: true
chunks:
myshardrs01 2
myshardrs02 2
{ "age" : { "$minKey" : 1 } } -->> { "age" : 0 } on : myshardrs01 Timestamp(2, 0)
{ "age" : 0 } -->> { "age" : 49 } on : myshardrs02 Timestamp(3, 1)
{ "age" : 49 } -->> { "age" : 119 } on : myshardrs02 Timestamp(2, 3)
{ "age" : 119 } -->> { "age" : { "$maxKey" : 1 } } on : myshardrs01 Timestamp(3, 0)
articledb.comment
shard key: { "nickname" : "hashed" }
unique: false
balancing: true
chunks:
myshardrs01 2
myshardrs02 2
{ "nickname" : { "$minKey" : 1 } } -->> { "nickname" : NumberLong("-4611686018427387902") } on : myshardrs01 Timestamp(1, 0)
{ "nickname" : NumberLong("-4611686018427387902") } -->> { "nickname" : NumberLong(0) } on : myshardrs01 Timestamp(1, 1)
{ "nickname" : NumberLong(0) } -->> { "nickname" : NumberLong("4611686018427387902") } on : myshardrs02 Timestamp(1, 2)
{ "nickname" : NumberLong("4611686018427387902") } -->> { "nickname" : { "$maxKey" : 1 } } on : myshardrs02 Timestamp(1, 3)
{ "_id" : "config", "primary" : "config", "partitioned" : true }
config.system.sessions
shard key: { "_id" : 1 }
unique: false
balancing: true
chunks:
myshardrs01 512
myshardrs02 512
too many chunks to print, use verbose if you want to force print
- 退出連接,重新連接服務(wù),使用普通權(quán)限帳號(hào)訪問(wèn)數(shù)據(jù):
[root@dev mongodb]# /opt/mongodb/bin/mongo --port 27017
mongos> use articledb
switched to db articledb
mongos> db.auth("bobo","123456")
1
mongos> show collections
author
comment
mongos> db.comment.count()
1000