$ mongod.exe --port=27017 --dbpath=./backup1 --replSet=backup $ mongod.exe 127.0.0.1:27017 > db.createRole({role:'sysadmin',roles:[],privileges:[{resource:{anyResource:true},actions:['anyAction']}]}) { "role" : "sysadmin", "roles" : [ ], "privileges" : [ { "resource" : { "anyResource" : true }, "actions" : [ "anyAction" ] } ] } > db.createUser({user:'346243440@qq.com',pwd:'xxxx',roles:[{role:'sysadmin',db:'admin'}]}) Successfully added user: { "user" : "346243440@qq.com", "roles" : [ { "role" : "sysadmin", "db" : "admin" } ] }
$ mongo.exe 127.0.0.1:27017 > use admin > show dbs # 报错了 2017-09-01T14:31:24.411+0800 E QUERY Error: listDatabases failed:{ "errmsg" : "not authorized on admin to execute command { listDatabases:... > db.auth('346243440@qq.com',xxxx) > 1 # 认证成功
> use admin > db.auth('3462...',xxx) > db.system.users.find()
参考文章
$ openssl rand -base64 1024 > mongodb.key
参考文章
参考文章
$ mongod.exe --port=27017 --dbpath=./backup1 --replSet=backup --keyFile "mongodb.key" $ mongod.exe --port=27018 --dbpath=./backup2 --replSet=backup --keyFile "mongodb.key" $ mongo.exe 127.0.0.1:27017 > backup:PRIMARY> use admin switched to db admin backup:PRIMARY> db.auth('a','a') 1 > backup:PRIMARY> show dbs admin 0.078GB local 1.078GB
rs.slaveOk() 打开可读权限
$ mongo.exe 127.0.0.1:27018 > use admin > db.auth('a','a') > show dbs # 报错如下 Error: listDatabases failed:{ "note" : "from execCommand", "ok" : 0, "errmsg" : "not master" } > rs.slaveOk() # 打开可读权限 > backup:PRIMARY> show dbs admin 0.078GB local 1.078GB
mongodb v.3.xxx 版本
> db.addUser("a","b") 2017-09-01T09:22:37.004+0800 E QUERY TypeError: Property 'addUser' of object admin is not a function at (shell):1:4 >
原来在mongodb3.0中addUser已被废弃,具体参考:
参考文章
> db.createUser({user:'a',pwd:'a',roles:['readWrite','dbAdmin']})
报错了 :
> db.createUser({user:'a',pwd:'a',roles:['readWrite','dbAdmin']}) 2017-09-01T11:24:29.549+0800 E QUERY Error: couldn't add user: not master at Error () at DB.createUser (src/mongo/shell/db.js:1101:11) at (shell):1:4 at src/mongo/shell/db.js:1101
查看 rs.status();发现当前连接的mongo 不是 primary,(是由于我建立了多个 replSet)
切换到 replSet Primary后
> db.createUser({user:'a',pwd:'a',roles:['readWrite','dbAdmin']}) Successfully added user: { "user" : "a", "b" : [ "readWrite", "dbAdmin" ] } >
连接mongodb slave报错:
2017-09-01T12:29:43.064+0800 E QUERY Error: listDatabases failed:{ "note" : "from execCommand", "ok" : 0, "errmsg" : "not master" }
解决: rs.slaveOk()