## mongodb的用户管理(认证管理)
-
用户分三种
全局用户
数据库对应用户
只读用户
### 创建全局用户(全局用户只能在admin账户下创建)
-
创建了一个名为zhuima,密码为zhuima的全局账户
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
[root@redis ~]# hostnameredis.unix178.com[root@redis ~]# mongoMongoDB shell version: 2.4.6connecting to: test> show dbslocal0.078125GB> use adminswitched to db admin> db.addUser("zhuima","zhuima"){"user" : "zhuima","readOnly" : false,"pwd" : "214c77cbc6bc7d26f28022c30496223d","_id" : ObjectId("53cbcb3cc5761ac13c7f6614")}> |
### 开启配置文件中的auth = true选项
|
1
2
3
4
5
|
[root@redis ~]# sed -n '/auth/p' /etc/mongodb.conf#noauth = true#auth = trueauth = true[root@redis ~]# |
### 重启mongodb进行验证 这里可以看到我们进行show的时候提示没权限
|
1
2
3
4
5
6
|
[root@redis ~]# mongoMongoDB shell version: 2.4.6connecting to: test> show dbsSun Jul 20 14:02:01.765 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46> |
### test数据库是默认进入的目录,如果你不想进入test数据库,mongo 后面跟上--nodb即可
### 想要切换到全局用户时,必须先要进入admin数据库才可以
|
1
2
3
4
5
6
7
8
9
10
11
|
[root@redis ~]# mongoMongoDB shell version: 2.4.6connecting to: test> use adminswitched to db admin> db.auth("zhuima","zhuima")1> show dbsadmin0.203125GBlocal0.078125GB> |
### 创建对应数据库的用户
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
> use zhuimaswitched to db zhuima> info = {info = {Name:"zhuima",Age:26,Gender:"F",Address:"Beijing China",Work:"Engineer",Other:"DevOps"}... ... > info = {Name:"zhuima",Age:26,Gender:"F",Address:"Beijing China",Work:"Engineer",Other:"DevOps"}{"Name" : "zhuima","Age" : 26,"Gender" : "F","Address" : "Beijing China","Work" : "Engineer","Other" : "DevOps"}> db.addUser("nick","zhuima"){"user" : "nick","readOnly" : false,"pwd" : "79e274165fd09b1902705535f24eecf9","_id" : ObjectId("53cbcd00a6852f086df7d087")} |
### 可以看出nick用户只能对zhuima这个数据库进行权限操作
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
[root@redis ~]# mongoMongoDB shell version: 2.4.6connecting to: test> use zhuimaswitched to db zhuima> db.auth("nick","zhuima")1> show dbsSun Jul 20 14:08:02.743 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46> show collectionssystem.indexessystem.users> db.system.users.find(){ "_id" : ObjectId("53cbcd00a6852f086df7d087"), "user" : "nick", "readOnly" : false, "pwd" : "79e274165fd09b1902705535f24eecf9" }> info = {Name:"zhuima",Age:26,Gender:"F",Address:"Beijing China",Work:"Engineer",Other:"DevOps"}{"Name" : "zhuima","Age" : 26,"Gender" : "F","Address" : "Beijing China","Work" : "Engineer","Other" : "DevOps"}> db.student.insert(info)> db.student.find(){ "_id" : ObjectId("53cbcd71d89972ce7ecf83c1"), "Name" : "zhuima", "Age" : 26, "Gender" : "F", "Address" : "Beijing China", "Work" : "Engineer", "Other" : "DevOps" }> |
### 增加一个只读用户
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
> db.addUser("kale","zhuima",True)Sun Jul 20 14:10:33.956 ReferenceError: True is not defined> db.addUser("kale","zhuima",true){"user" : "kale","readOnly" : true,"pwd" : "c705496ba883d8a8acf0855396fa8b5e","_id" : ObjectId("53cbcde3d89972ce7ecf83c2")}> message = {Name:"kale",Age:26,Gender:"F"}{ "Name" : "kale", "Age" : 26, "Gender" : "F" }> db.auth("kale","zhuima")1> message = {Name:"kale",Age:26,Gender:"F"}{ "Name" : "kale", "Age" : 26, "Gender" : "F" }> show collectionsstudentsystem.indexessystem.users> db.student.insert(message)not authorized for insert on zhuima.student> db.auth("nick","zhuima")1> db.student.insert(message)> db.student.find(){ "_id" : ObjectId("53cbcd71d89972ce7ecf83c1"), "Name" : "zhuima", "Age" : 26, "Gender" : "F", "Address" : "Beijing China", "Work" : "Engineer", "Other" : "DevOps" }{ "_id" : ObjectId("53cbce5fd89972ce7ecf83c4"), "Name" : "kale", "Age" : 26, "Gender" : "F" }> |
### 删除一个用户
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
> db.system.users.find(){ "_id" : "admin.zhuima", "user" : "zhuima", "db" : "admin", "credentials" : { "MONGODB-CR" : "214c77cbc6bc7d26f28022c30496223d" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }{ "_id" : "zhuima.nick", "user" : "nick", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "b8b8d091c8b634fe785f41cf3339d9ec" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }{ "_id" : "zhuima.test", "user" : "test", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "a6de521abefc2fed4f5876855a3484f5" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }{ "_id" : "zhuima.kale", "user" : "kale", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "a47cb6627c18898317171265eeea47e2" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }> use zhuimaswitched to db zhuima> db.dropUser("test")true> show collectionspersonsystem.indexes> use adminswitched to db admin> db.system.users.find(){ "_id" : "admin.zhuima", "user" : "zhuima", "db" : "admin", "credentials" : { "MONGODB-CR" : "214c77cbc6bc7d26f28022c30496223d" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }{ "_id" : "zhuima.nick", "user" : "nick", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "b8b8d091c8b634fe785f41cf3339d9ec" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }{ "_id" : "zhuima.kale", "user" : "kale", "db" : "zhuima", "credentials" : { "MONGODB-CR" : "a47cb6627c18898317171265eeea47e2" }, "roles" : [ { "role" : "dbOwner", "db" : "zhuima" } ] }> |
### 用户管理后记
-
多用help 类似db.help()
-
看官方文档,然后把命令都敲一遍
-
多实践才是王道
## 来一些系统的基本的查看管理命令
### help指令
-
多用help,你会发现原来世界那么美好
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
> helpdb.help() help on db methodsdb.mycoll.help() help on collection methodssh.help() sharding helpersrs.help() replica set helpershelp admin administrative helphelp connect connecting to a db helphelp keys key shortcutshelp misc misc things to knowhelp mr mapreduceshow dbs show database namesshow collections show collections in current databaseshow users show users in current databaseshow profile show most recent system.profile entries with time >= 1msshow logs show the accessible logger namesshow log [name] prints out the last segment of log in memory, 'global' is defaultuse <db_name> set current databasedb.foo.find() list objects in collection foodb.foo.find( { a : 1 } ) list objects in foo where a == 1it result of the last line evaluated; use to further iterateDBQuery.shellBatchSize = x set default number of items to display on shellexit quit the mongo shell> db.help()DB methods:db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]db.auth(username, password)db.cloneDatabase(fromhost)db.commandHelp(name) returns the help for the commanddb.copyDatabase(fromdb, todb, fromhost)db.createCollection(name, { size : ..., capped : ..., max : ... } )db.createUser(userDocument)db.currentOp() displays currently executing operations in the dbdb.dropDatabase()db.eval(func, args) run code server-sidedb.fsyncLock() flush data to disk and lock server for backupsdb.fsyncUnlock() unlocks server following a db.fsyncLock()db.getCollection(cname) same as db['cname'] or db.cnamedb.getCollectionNames()db.getLastError() - just returns the err msg stringdb.getLastErrorObj() - return full status objectdb.getMongo() get the server connection objectdb.getMongo().setSlaveOk() allow queries on a replication slave serverdb.getName()db.getPrevError()db.getProfilingLevel() - deprecateddb.getProfilingStatus() - returns if profiling is on and slow thresholddb.getReplicationInfo()db.getSiblingDB(name) get the db at the same server as this onedb.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if setdb.hostInfo() get details about the server's hostdb.isMaster() check replica primary statusdb.killOp(opid) kills the current operation in the dbdb.listCommands() lists all the db commandsdb.loadServerScripts() loads all the scripts in db.system.jsdb.logout()db.printCollectionStats()db.printReplicationInfo()db.printShardingStatus()db.printSlaveReplicationInfo()db.dropUser(username)db.repairDatabase()db.resetError()db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }db.serverStatus()db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=alldb.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the dbdb.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the dbdb.setVerboseShell(flag) display extra information in shell outputdb.shutdownServer()db.stats()db.version() current version of the server> |
### 查看当前所在数据库位置
-
第一种方式
|
1
2
3
4
|
> > db.statusadmin.status> |
-
第二种方式
|
1
2
3
|
> db.getName();admin> |
### 当前数据库版本
|
1
2
3
|
> db.version()2.6.3> |
### 查看当前数据库中的包含的集合
|
1
2
3
4
|
> show collectionssystem.indexessystem.userssystem.version |
### 删除数据库
-
切换到该数据库目录下,进行drop操作即可
|
1
2
3
4
5
6
7
8
9
10
11
12
|
> show dbsadmin 0.078GBlocal 1.078GBzhuima 0.078GB> use zhuimaswitched to db zhuima> db.dropDatabase(){ "dropped" : "zhuima", "ok" : 1 }> show dbsadmin 0.078GBlocal 1.078GB> |
### 查看各collection的状态
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
> use adminswitched to db admin> db.printCollectionStats()system.indexes{"ns" : "admin.system.indexes","count" : 3,"size" : 336,"avgObjSize" : 112,"storageSize" : 8192,"numExtents" : 1,"nindexes" : 0,"lastExtentSize" : 8192,"paddingFactor" : 1,"systemFlags" : 0,"userFlags" : 1,"totalIndexSize" : 0,"indexSizes" : {},"ok" : 1}---system.users{"ns" : "admin.system.users","count" : 3,"size" : 720,"avgObjSize" : 240,"storageSize" : 8192,"numExtents" : 1,"nindexes" : 2,"lastExtentSize" : 8192,"paddingFactor" : 1,"systemFlags" : 1,"userFlags" : 1,"totalIndexSize" : 16352,"indexSizes" : {"_id_" : 8176,"user_1_db_1" : 8176},"ok" : 1}---system.version{"ns" : "admin.system.version","count" : 1,"size" : 48,"avgObjSize" : 48,"storageSize" : 8192,"numExtents" : 1,"nindexes" : 1,"lastExtentSize" : 8192,"paddingFactor" : 1,"systemFlags" : 1,"userFlags" : 1,"totalIndexSize" : 8176,"indexSizes" : {"_id_" : 8176},"ok" : 1}---> |
### 查看collection数据的大小
|
1
2
3
|
> db.system.users.dataSize()720> |
本文出自 “追马” 博客,请务必保留此出处http://lovelace.blog.51cto.com/1028430/1441033