设为首页 收藏本站
查看: 1013|回复: 0

[经验分享] mongodb之用户管理与系统管理常用命令

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2014-7-22 08:46:55 | 显示全部楼层 |阅读模式
## mongodb的用户管理(认证管理)
  • 用户分三种   

       全局用户

         数据库对应用户

         只读用户



### 创建全局用户(全局用户只能在admin账户下创建)
  • 创建了一个名为zhuima,密码为zhuima的全局账户


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[iyunv@redis ~]# hostname
redis.unix178.com
[iyunv@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> show dbs
local0.078125GB
> use admin
switched to db admin
> db.addUser("zhuima","zhuima")
{
"user" : "zhuima",
"readOnly" : false,
"pwd" : "214c77cbc6bc7d26f28022c30496223d",
"_id" : ObjectId("53cbcb3cc5761ac13c7f6614")
}
>




### 开启配置文件中的auth = true选项
1
2
3
4
5
[iyunv@redis ~]# sed -n '/auth/p' /etc/mongodb.conf
#noauth = true
#auth = true
auth = true
[iyunv@redis ~]#




### 重启mongodb进行验证 这里可以看到我们进行show的时候提示没权限
1
2
3
4
5
6
[iyunv@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> show dbs
Sun 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
[iyunv@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> use admin
switched to db admin
> db.auth("zhuima","zhuima")
1
> show dbs
admin0.203125GB
local0.078125GB
>




### 创建对应数据库的用户
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
> use zhuima
switched 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
[iyunv@redis ~]# mongo
MongoDB shell version: 2.4.6
connecting to: test
> use zhuima
switched to db zhuima
> db.auth("nick","zhuima")
1
> show dbs
Sun Jul 20 14:08:02.743 listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46
> show collections
system.indexes
system.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 collections
student
system.indexes
system.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 zhuima
switched to db zhuima
> db.dropUser("test")
true
> show collections
person
system.indexes
> use admin
switched 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
> 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
> 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 command
db.copyDatabase(fromdb, todb, fromhost)
db.createCollection(name, { size : ..., capped : ..., max : ... } )
db.createUser(userDocument)
db.currentOp() displays currently executing operations in the db
db.dropDatabase()
db.eval(func, args) run code server-side
db.fsyncLock() flush data to disk and lock server for backups
db.fsyncUnlock() unlocks server following a db.fsyncLock()
db.getCollection(cname) same as db['cname'] or db.cname
db.getCollectionNames()
db.getLastError() - just returns the err msg string
db.getLastErrorObj() - return full status object
db.getMongo() get the server connection object
db.getMongo().setSlaveOk() allow queries on a replication slave server
db.getName()
db.getPrevError()
db.getProfilingLevel() - deprecated
db.getProfilingStatus() - returns if profiling is on and slow threshold
db.getReplicationInfo()
db.getSiblingDB(name) get the db at the same server as this one
db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
db.hostInfo() get details about the server's host
db.isMaster() check replica primary status
db.killOp(opid) kills the current operation in the db
db.listCommands() lists all the db commands
db.loadServerScripts() loads all the scripts in db.system.js
db.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=all
db.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the db
db.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the db
db.setVerboseShell(flag) display extra information in shell output
db.shutdownServer()
db.stats()
db.version() current version of the server
>



### 查看当前所在数据库位置
  • 第一种方式

1
2
3
4
>
> db.status
admin.status
>



  • 第二种方式

1
2
3
> db.getName();
admin
>




### 当前数据库版本
1
2
3
> db.version()
2.6.3
>




### 查看当前数据库中的包含的集合
1
2
3
4
> show collections
system.indexes
system.users
system.version




### 删除数据库
  • 切换到该数据库目录下,进行drop操作即可

1
2
3
4
5
6
7
8
9
10
11
12
> show dbs
admin   0.078GB
local   1.078GB
zhuima  0.078GB
> use zhuima
switched to db zhuima
> db.dropDatabase()
{ "dropped" : "zhuima", "ok" : 1 }
> show dbs
admin  0.078GB
local  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 admin
switched 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
>




### 增删查改的文章请移步到上篇文章




运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-22446-1-1.html 上篇帖子: mongodb之简单的CRUD 下篇帖子: mongodb之master/slave模式 用户
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表