时间:2021-07-01 10:21:17 帮助过:4人阅读
下面创建数据库tage,并给tage创建用户: > use tage switched to db tage > db.addUser("tage","123") { "user" : "tage", "readOnly" : false, "pwd" : "1f66d5c4223029536080d41febe0ec33" } 在admin库中创建root用户: > use admin switched to db admin > db.addUser("root","123456") { "user" : "root", "readOnly" : false, "pwd" : "34e5772aa66b703a319641d42a47d696" }
3、验证用户
> db.auth("root","123") 0 密码错误,返回0,验证失败 > db.auth("root","123456") 1 验证成功,返回1
下面试验用户权限设置: $ ./mongo 登录时不加用户名与密码 MongoDB shell version: 1.8.1 connecting to: test > use tage switched to db tage > db.system.users.find() error: { "$err" : "unauthorized db:tage lock type:-1 client:127.0.0.1", "code" : 10057
4、以上验证说明,登录时不指定用户名与密码,就会报错。下面指定用户与密码
$ ./mongo -uroot -p123456 指定用户与密码,但是不指定库名 MongoDB shell version: 1.8.1 connecting to: test Wed Aug 3 21:30:42 uncaught exception: login failed exception: login failed mongodb登录时默认连接test库,如果登录时不指定库名,就会报错
5、下面以tage库的用户名登录进行验证:
$ ./mongo tage -utage -p123 MongoDB shell version: 1.8.1 connecting to: tage > db.system.users.find() 对所属自己的库进行操作,有权限 { "_id" : ObjectId("4e394c696b50a56254359088"), "user" : "tage", "readOnly" : false, "pwd" : "1f66d5c4223029536080d41febe0ec33" } > use admin switched to db admin > db.system.users.find() 对其他库操作,没有权限 error: { "$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1", "code" : 10057 }
6、下面以admin库下的root用户登录进行验证:
./mongo admin -uroot -p123456 MongoDB shell version: 1.8.1 connecting to: admin > db.system.users.find() { "_id" : ObjectId("4e394caf6b50a56254359089"), "user" : "root", "readOnly" : false, "pwd" : "34e5772aa66b703a319641d42a47d696" } > use tage switched to db tage > db.system.users.find() 对其他库进行操作,有权限 { "_id" : ObjectId("4e394c696b50a56254359088"), "user" : "tage", "readOnly" : false, "pwd" : "1f66d5c4223029536080d41febe0ec33" }
7. mongodb的远程用户连接
语法结构:mongo –uusername –ppwd ServerIP:port/dbname 其中port默认为27017 $ ./mongo -uroot -p123456 192.168.2.150/admin MongoDB shell version: 1.8.1 connecting to: 192.168.2.150/admin > db.system.users.find() { "_id" : ObjectId("4e394caf6b50a56254359089"), "user" : "root", "readOnly" : false, "pwd" : "34e5772aa66b703a319641d42a47d696" }
MongoDB的授权和权限
标签: