- #--------------------------------------------
- # 此脚本用于开启Mongodb数据库的副本集功能
- # author:cch
- # date:2022-09-13
- #--------------------------------------------
-
- #!/bin/bash
-
- #admin用户的密码
- admin_pwd="admin"
-
- #mongodb服务端口
- server_port=27017
-
- #需要操作的数据库
- database="inventory"
-
- #新建用户的用户名
- new_user_name="newUser"
- #新建用户的密码
- new_user_pwd="123456"
-
- #开启副本集
- mongo localhost:${server_port}/${database} <<-EOF
- rs.initiate({
- _id: "rs0",
- members: [ { _id: 0, host: "localhost:27017" } ]
- });
- EOF
-
- #是否存在admin账户,不存在会创建一个,密码是上面指定的密码
- #如果已经存在了admin账户,可以把这3行注释掉
- mongo localhost:${server_port}/admin <<-EOF
- db.createUser({ user: 'admin', pwd: '${admin_pwd}', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
- EOF
-
- # 配置mongodb事件监听角色
- mongo -u admin -p ${admin_pwd} localhost:${server_port}/admin <<-EOF
- db.runCommand({
- createRole: "listDatabases",
- privileges: [
- { resource: { cluster : true }, actions: ["listDatabases"]}
- ],
- roles: []
- });
- db.runCommand({
- createRole: "readChangeStream",
- privileges: [
- { resource: { db: "", collection: ""}, actions: [ "find", "changeStream" ] }
- ],
- roles: []
- });
- EOF
-
-
- sleep 1
- #创建用户
- mongo -u admin -p ${admin_pwd} localhost:${server_port}/admin <<-EOF
- use ${database}
-
- db.createUser({
- user: '${new_user_name}',
- pwd: '${new_user_pwd}',
- roles: [
- { role: "readWrite", db: "${database}" },
- { role: "read", db: "local" },
- { role: "listDatabases", db: "admin" },
- { role: "readChangeStream", db: "admin" },
- { role: "read", db: "config" },
- { role: "read", db: "admin" }
- ]
- });
- EOF
- echo "Created users"