在开启MongoDB 服务时不添加任何参数时,可以对数据库任意操作,而且可以远程访问数据库。如果启动的时候指定—auth参数,可以对数据库进行用户验证。
$ ./mongod --auth >> mongodb.log & 开启
./mongo
MongoDB shell version: 1.8.1
connecting to: test
show dbs
admin (empty)
local (empty)
在刚安装完毕的时候MongoDB都默认有一个admin数据库,而admin.system.users中将会保存比在其它数据库中设置的用户权限更大的用户信息。
当admin.system.users中一个用户都没有时,即使mongod启动时添加了–auth参数,如果没有在admin数据库中添加用户,此时不进行任何认证还是可以做任何操作,直到在admin.system.users中添加了一个用户。
下面创建数据库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"
}
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
}
$ ./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库,如果登录时不指定库名,就会报错
$ ./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
}
./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” }
语法结构: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” }
原链接地址:https://blog.csdn.net/joeyon1985/article/details/45668485