Anolis8mongodb

AnolisOS 8 下MongoDB的安装和配置

2023-01-09  本文已影响0人  前浪浪奔浪流

部署系统:AnolisOS 8
部署版本:MongoDB4.4.18

1、mongdb官网下载系统版本对应的数据库

1.1确认操作系统版本和内核版本

[root@anolis8 ~]# cat /etc/anolis-release 
Anolis OS release 8.4
[root@anolis8 ~]#  uname -a
Linux anolis8 4.18.0-372.32.1.an8_6.x86_64 #1 SMP Fri Oct 28 12:06:23 CST 2022 x86_64 x86_64 x86_64 GNU/Linux

1.2下载mongodb4.4.18

官网:https://www.mongodb.com/try/download/community

下载:


image.png
[root@anolis8 ~]# wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel80-4.4.18.tgz

2、MongoDB的安装部署

2.1 创建用户和用户组

[root@anolis8 ~]# useradd mongod
[root@anolis8 ~]# passwd mongod
更改用户 mongod 的密码 。
新的 密码:
无效的密码: 密码未通过字典检查 - 太简单或太有规律
重新输入新的 密码:
passwd:所有的身份验证令牌已经成功更新。

注意:输入用户密码,此处mongod用户使用的密码:mondb123

2.2 创建所需的目录

[root@anolis8 ~]# mkdir -p /data/mongodb/{conf,log,data}
[root@anolis8 ~]# ll /data
总用量 0
drwxr-xr-x 5 root   root   41 1月   7 16:41 mongodb
drwxr-xr-x 2 nobody nobody 19 12月 22 11:05 test
-rw-r--r-- 1 root   root    0 10月  4 16:46 test.log
[root@anolis8 ~]# ll /data/mongodb/
总用量 0
drwxr-xr-x 2 root root 6 1月   7 16:41 conf
drwxr-xr-x 2 root root 6 1月   7 16:41 data
drwxr-xr-x 2 root root 6 1月   7 16:41 log

conf:存放配置文件
data:数据目录
log:日志目录

2.3 解压软件

[root@anolis8 ~]# tar xvf mongodb-linux-x86_64-rhel80-4.4.18.tgz 
mongodb-linux-x86_64-rhel80-4.4.18/LICENSE-Community.txt
mongodb-linux-x86_64-rhel80-4.4.18/MPL-2
mongodb-linux-x86_64-rhel80-4.4.18/README
mongodb-linux-x86_64-rhel80-4.4.18/THIRD-PARTY-NOTICES
mongodb-linux-x86_64-rhel80-4.4.18/bin/install_compass
mongodb-linux-x86_64-rhel80-4.4.18/bin/mongo
mongodb-linux-x86_64-rhel80-4.4.18/bin/mongod
mongodb-linux-x86_64-rhel80-4.4.18/bin/mongos

[root@anolis8 ~]# cp -r mongodb-linux-x86_64-rhel80-4.4.18/bin/ /data/mongodb
[root@anolis8 ~]# ll /data/mongodb/
总用量 0
drwxr-xr-x 2 root root 70 1月   7 16:58 bin
drwxr-xr-x 2 root root  6 1月   7 16:41 conf
drwxr-xr-x 2 root root  6 1月   7 16:41 data
drwxr-xr-x 2 root root  6 1月   7 16:41 log

2.4设置数据库目录权限

[root@anolis8 ~]# ll /data/mongodb/bin/
总用量 198100
-rwxr-xr-x 1 root root    15205 1月   7 16:58 install_compass
-rwxr-xr-x 1 root root 53815112 1月   7 16:58 mongo
-rwxr-xr-x 1 root root 83468024 1月   7 16:58 mongod
-rwxr-xr-x 1 root root 65549448 1月   7 16:58 mongos

[root@anolis8 ~]# chown -R mongod:mongod /data/mongodb
[root@anolis8 ~]# ll /data/mongodb/bin/
总用量 198100
-rwxr-xr-x 1 mongod mongod    15205 1月   7 16:58 install_compass
-rwxr-xr-x 1 mongod mongod 53815112 1月   7 16:58 mongo
-rwxr-xr-x 1 mongod mongod 83468024 1月   7 16:58 mongod
-rwxr-xr-x 1 mongod mongod 65549448 1月   7 16:58 mongos
[root@anolis8 ~]# ll /data/mongodb/
总用量 0
drwxr-xr-x 2 mongod mongod 70 1月   7 16:58 bin
drwxr-xr-x 2 mongod mongod  6 1月   7 16:41 conf
drwxr-xr-x 2 mongod mongod  6 1月   7 16:41 data
drwxr-xr-x 2 mongod mongod  6 1月   7 16:41 log

2.5 配置环境变量

[root@anolis8 ~]# su - mongod
[mongod@anolis8 ~]$ pwd
/home/mongod

添加用户的环境变量,打开环境变量文件后在末尾添加如下内容:
[mongod@anolis8 ~]$ vim .bash_profile
export PATH=/data/mongodb/bin:$PATH

加载环境变量
[mongod@anolis8 ~]$ source .bash_profile
[mongod@anolis8 ~]$  echo $PATH
/data/mongodb/bin:/home/mongod/.local/bin:/home/mongod/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/jdk1.8.0_11/bin

2.6启动数据库

[mongod@anolis8 root]$  mongod --dbpath=/data/mongodb/data --logpath=/data/mongodb/log/mongodb.log --port=27017 --logappend --fork 

参数详解:
--dbpath:数据存放目录
--logpath:日志目录文件
--port: 数据库端口
--logappend:日志追加方式

[mongod@anolis8 root]$ ps -ef|grep mongodb
mongod    135021       1  2 17:24 ?        00:00:01 mongod --dbpath=/data/mongodb/data --logpath=/data/mongodb/log/mongodb.log --port=27017 --logappend --fork
mongod    135103  134997  0 17:25 pts/0    00:00:00 grep --color=auto mongodb

2.7 登陆到数据库

[mongod@anolis8 root]$ mongo
MongoDB shell version v4.4.18
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("26dd4902-6fb0-42d7-abd2-a0a859550169") }
MongoDB server version: 4.4.18
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
    https://community.mongodb.com
---
The server generated these startup warnings when booting: 
        2023-01-07T17:24:05.242+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2023-01-07T17:24:05.242+08:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
        2023-01-07T17:24:05.243+08:00: Soft rlimits too low
        2023-01-07T17:24:05.243+08:00:         currentValue: 1024
        2023-01-07T17:24:05.243+08:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> 
注:>:表示已经进入到mongo的shell命令行,可以对数据库进行管理。

2.8数据库进程和端口检查

[mongod@anolis8 root]$ ps -ef|grep mongo
root      134985  130512  0 17:23 pts/0    00:00:00 su mongod
mongod    134987       1  0 17:23 ?        00:00:00 /usr/lib/systemd/systemd --user
mongod    134989  134987  0 17:23 ?        00:00:00 (sd-pam)
mongod    134997  134985  0 17:23 pts/0    00:00:00 bash
mongod    135021       1  0 17:24 ?        00:00:27 mongod --dbpath=/data/mongodb/data --logpath=/data/mongodb/log/mongodb.log --port=27017 --logappend --fork
mongod    138105  134997  0 18:35 pts/0    00:00:00 ps -ef
mongod    138106  134997  0 18:35 pts/0    00:00:00 grep --color=auto mongo
[mongod@anolis8 root]$ netstat  -lntp|grep mong
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      135021/mongod

3、mongodb的配置文件及单库简洁配置

mongodb的配置文件格式是YMAL格式。可自定义为mongo.conf或按照项目业务名称自定义配置文件的名称即可,以.conf结尾。

3.1 mongodb配置文件详解

---系统日志模块
systemLog:
  destination: file   #Mongodb 日志输出的目的地,指定一个 file 或者 syslog,如果指定 file,必须指定 systemlog.path
  logAppend: true  #实例重启时,不创建新日志文件,在旧日志文件末尾继续添加
  path: /data/mongodb/log/mongo.log    #日志路径

---数据存储模块
storage:
  dbPath: /data/mongodb/data    #数据存储目录
  journal:       #回滚日志
    enabled: true
  directoryPerDB: true    #默认 false,不适用 inmemory engine

 engine:        #存储引擎3.2默认wiredTiger

 mmapv1:  #4.0开始启用 mmapv1存储引擎
    preallocDataFiles:  #启用或禁用数据文件的预分配。默认情况下,MongoDB不会预分配数据文件。
    nsSize:                 #默认16M命名空间文件的默认大小,即文件的结尾.ns。每个集合和索引都将计算为一个命名空间。
    quota:
        enforced:       #默认 false,启用或禁用每个数据库可以拥有的数字数据文件的最大限制
        maxFilesPerDB:      #默认8,每个数据库的数据文件数量的限制和enforced参数结合使用。。
    smallFiles:         #默认 false 选项减少数据文件的初始大小,使用大量的库存较小的文件
  wiredTiger:
     engineConfig:
        cacheSizeGB: 2   #将用于所有数据缓存的最大小
        journalCompressor:  #默认snappy,WiredTiger日志数据的压缩类型。
        directoryForIndexes: true #默认false 索引集合storage.dbPath存储在数据单独子目录
     collectionConfig:
        blockCompressor:  #默认snappy,用于压缩收集数据的默认压缩类型
     indexConfig:
        prefixCompression:   #默认 true启用或禁用索引数据的前缀压缩
  inMemory:
     engineConfig:
        inMemorySizeGB:     #默认值:物理RAM的50%少于1 GB

---进程控制模块
processManagement:    #使用处理系统守护进程的控制处理
  fork: true  # fork and run in background  后台运行
  pidFilePath: /data/mongodb/pid/mongod.pid  # location of pidfile 创建 pid 文件

---网络模块
net:
  port: 28017            #监听端口
  bindIp:  localhost,192.168.0.1     #绑定内网 ip,
  maxIncomingConnections: 5000  #mongos 或者 mongod 最大连接数,如果高于系统配置的最大连接阈值则不起作用
  #http:
    #enabled: true    #开启 http 接口确保生产环境中的REST API和JSON API都被禁用以防止潜在的数据暴露和***者的漏洞。

---安全认证模块
security:     #认证
  keyFile: /data/mongod/conf/keyfile  #秘钥文件的路径,用于 mongodb 分片集群或者副本集进行身份验证的共享秘钥
  clusterAuthMode: keyFile #集群的认证方式 keyFile 秘钥文件进行身份认证,推荐 x509证书认证
  authorization: enabled  #启用或者禁用基于角色的访问控制来管理每个用户对数据库资源和操作的访问 enabled 或者 disables
  javascriptEnabled:   #启用或者禁用服务端JavaScript 执行,禁用时不能使用JavaScript代码的服务端执行操作
  sasl:
     hostName: 
     serviceName: 
     saslauthdSocketPath: 
  enableEncryption:   #启用WiredTiger存储引擎的加密。您必须设置为true传递加密密钥和配置
  encryptionCipherMode:  #加密的模式适用于企业版
  encryptionKeyFile:  #通过KMIP 以外的进程管理密钥时的本地密钥文件的路径只有通过KMIP以外的进程管理密钥时才设置,需要saecurity.enableEncryption是true。

 kmip:
     keyIdentifier: 
     rotateMasterKey: 
     serverName: 
     port: 
     clientCertificateFile: 
     clientCertificatePassword: 
     serverCAFile: 

---副本集配置模块
replication:   #副本集用到的配置
   oplogSizeMB: 1024 #复制操作日志的大小,详细介绍见oplog文章,
   replSetName: eqxtest3  #副本集名称,同一个副本集的所有主机必须设置相同的名称
   secondaryIndexPrefetch:  #只用于 mmapv1存储引擎,默认二进制文件和相关操作索引加载到内存,none 不会加载,all 二次加载,_id_only出了已存在_id,不会加载其他索引
   enableMajorityReadConcern:  #默认 false

---分片集群配置模块
sharding:  #分片用到的配置
   clusterRole: shardsvr  #分片集群角色,configsvr作为配置服务启动,shardsvr 分片实例启动
   archiveMovedChunks:   #块迁移期间,一个分片不保存文档从分片迁移,默认 false
   autoSplit:  # 默认 true,启用或者禁用自动分片,
   configDB:  #mongos 分片集群实例必须制定相同的配置服务副本集名字,configDB: /cfg1.example.net:27017, cfg2.example.net:27017
   chunkSize:  #默认64M

注意:MongoDB 3.6以后开始,默认mongod和mongos绑定到localhost。如果部署的成员在不同的主机上运行,或者希望远程客户端连接到部署服务器,则必须指定--bind_ip或net.bindIp

3.2 mongodb配置文件案例

vim /data/mongodb/conf/mongo.conf

systemLog:
  destination: file
  path: "/data/mongodb/log/mongodb.log"
  logAppend: true
storage:
  journal:
    enabled: true
  dbPath: "/data/mongodb/data/"
processManagement:
  fork: true
net:
  port: 27017
  bindIp: 192.168.100.86,127.0.0.1

4 配置通过系统的systemd管理mongodb数据库服务

通过配置systemd后,可以像管理mysql服务一样管理mongodb服务。

4.1 systemd服务管理模板

在root账户下

vim /etc/systemd/system/mongod.service

[Unit]
Description=mongodb 
After=network.target remote-fs.target nss-lookup.target
[Service]
User=mongod
Type=forking
ExecStart=/data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf --shutdown
PrivateTmp=true  
[Install]
WantedBy=multi-user.target

参数详解:
ExecStart:启动数据库服务的脚本路径
ExecStop:关闭数据库服务的脚本路径
--config:配置文件的路径

systemctl daemon-reload

4.2、管理服务

[root@anolis8 ~]# systemctl restart mongod
[root@anolis8 ~]# systemctl stop mongod
[root@anolis8 ~]# systemctl start mongod

[root@mysql8-1 ~]# systemctl status mongod.service -l
● mongod.service - mongodb
Loaded: loaded (/etc/systemd/system/mongod.service; disabled; vendor preset: disabled)
Active: active (running) since 六 2022-02-19 15:03:38 CST; 1s ago
Process: 14738 ExecStart=/data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf (code=exited, status=0/SUCCESS)
Main PID: 14740 (mongod)
CGroup: /system.slice/mongod.service
└─14740 /data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf

2月 19 15:03:36 mysql8-1 systemd[1]: Starting mongodb...
2月 19 15:03:36 mysql8-1 mongod[14738]: about to fork child process, waiting until server is ready for connections.
2月 19 15:03:36 mysql8-1 mongod[14738]: forked process: 14740
2月 19 15:03:38 mysql8-1 mongod[14738]: child process started successfully, parent exiting
2月 19 15:03:38 mysql8-1 systemd[1]: Started mongodb.

5.

默认情况下,MongoDB实例启动运行时是没有启用用户访问权限控制的,也就是说,在实例本机服务器上都可以随意连接到实例进行各种操作,MongoDB不会对连接客户端进行用户验证,这是非常危险的。

可以通过以下的几种方式来保障 MongoDB的安全:

5.1使用新的端口,默认的 27017 端口如果一旦知道了IP就能连接上,太不安全.

5.2设置MongoDB的网络环境。最好将MongoDB部署到公司服务器内网,这样外网是访问不到的。公司内部访问使用VPN等。

5.3开启安全认证。认证要同时设置服务器之间的内部认证方式,同时设置客户端连接到集群的账号密码认证方式。为了强制开启用户访问控制(用户验证),则需要在MongoDB实例启动时使用选项 --auth 或在指定启动配置文件中添加选项 auth=true

相关概念

角色
在角色定义时可以包含一个或多个已存在的角色,新创建的角色会继承包含的角色所有的权限。在同一个数据库中,新创建角色可以继承其他角色的权限,在 admin 数据库中创建的角色可以继承在其它任意数据库中角色的权限。

角色相关命令

# 查询所有角色权限(仅用户自定义角色)
> db.runCommand({ rolesInfo: 1 })
{ "roles" : [ ], "ok" : 1 }
# 查询所有角色权限(包含内置角色)
> db.runCommand({ rolesInfo: 1, showBuiltinRoles: true })
{
    "roles" : [
        {
            "role" : "dbAdmin",
            "db" : "test",
            "isBuiltin" : true,
            "roles" : [ ],
            "inheritedRoles" : [ ]
        },
        {
            "role" : "dbOwner",
            "db" : "test",
            "isBuiltin" : true,
            "roles" : [ ],
            "inheritedRoles" : [ ]
        },
        {
            "role" : "enableSharding",
            "db" : "test",
            "isBuiltin" : true,
            "roles" : [ ],
            "inheritedRoles" : [ ]
        },
        {
            "role" : "read",
            "db" : "test",
            "isBuiltin" : true,
            "roles" : [ ],
            "inheritedRoles" : [ ]
        },
        {
            "role" : "readWrite",
            "db" : "test",
            "isBuiltin" : true,
            "roles" : [ ],
            "inheritedRoles" : [ ]
        },
        {
            "role" : "userAdmin",
            "db" : "test",
            "isBuiltin" : true,
            "roles" : [ ],
            "inheritedRoles" : [ ]
        }
    ],
    "ok" : 1
}

# 查询当前数据库中的某角色的权限
db.runCommand({ rolesInfo: "<rolename>" })

# 查询其它数据库中指定的角色权限
db.runCommand({ rolesInfo: { role: "<rolename>", db: "<database>" } }

# 查询多个角色权限
db.runCommand( { rolesInfo: [ "<rolename>", { role: "<rolename>", db: "<database>" }, ... ] } )
常用的内置角色:
角色说明:
角色 权限描述
read 可以读取指定数据库中任何数据。
readWrite 可以读写指定数据库中任何数据,包括创建、重命名、删除集合。
readAnyDatabase 可以读取所有数据库中任何数据(除了数据库confifig和local之外)。
readWriteAnyDatabase 可以读写所有数据库中任何数据(除了数据库confifig和local之外)。
userAdminAnyDatabase 可以在指定数据库创建和修改用户(除了数据库confifig和local之外)。
dbAdminAnyDatabase 可以读取任何数据库以及对数据库进行清理、修改、压缩、获取统计信息、执行检查等操作(除了数据库confifig和local之外)。
dbAdmin 可以读取指定数据库以及对数据库进行清理、修改、压缩、获取统计信息、执行检查等操作。
userAdmin 可以在指定数据库创建和修改用户。
clusterAdmin 可以对整个集群或数据库系统进行管理操作。
backup 备份MongoDB数据最小的权限。
restore 从备份文件中还原恢复MongoDB数据(除了system.profifile集合)的权限。
root 超级账号,超级权限
dbOwner 即 readWrite + dbAdmin + dbAdmin
[root@anolis8 ~]# vim /data/mongodb/conf/mongo.conf

systemLog:
  destination: file
  path: "/data/mongodb/log/mongodb.log"
  logAppend: true
storage:
  journal:
    enabled: true
  dbPath: "/data/mongodb/data/"
processManagement:
  fork: true
net:
  port: 27017
  bindIp: 192.168.100.86,127.0.0.1

用这个配置文件启动,是未开启认证的方式。

[root@anolis8 ~]# su mongod
[mongod@anolis8 root]$ mongo --port 27017
MongoDB shell version v4.4.18
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("1aef7103-a41f-4ede-8174-166e50697ccc") }
MongoDB server version: 4.4.18
---
The server generated these startup warnings when booting: 
        2023-01-08T16:49:07.458+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2023-01-08T16:49:07.458+08:00: Soft rlimits too low
        2023-01-08T16:49:07.458+08:00:         currentValue: 1024
        2023-01-08T16:49:07.458+08:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> 
#创建两个管理员用户,一个是系统的超级管理员myroot,一个是admin库的管理用户myadmin:
> use admin
switched to db admin
> db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
> db.createUser({user:"myadmin",pwd:"123456",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Successfully added user: {
    "user" : "myadmin",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
#查看已创建了的用户的情况
> db.system.users.find()
{ "_id" : "admin.myroot", "userId" : UUID("de8dabd6-c2dc-4443-9e59-16f94940da60"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "/JAWRQVnNNHbWpWawFr6Iw==", "storedKey" : "qXwCwG9OiEoU9LlIm/lyEdq1iXg=", "serverKey" : "Tbfc9WjwnuwlxOidswV2m1qdxpQ=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "l95mqnLX3ipYn5PIHXCOMnMlFzeJGhD1YeUZ1Q==", "storedKey" : "RpQv9Kv2eulbBfANya4tB6SAyfC2RiFhAHrXyUem+vo=", "serverKey" : "fPGHqIU1t8wZGRaYdiNSKyBbypBwdAAocqS9lneRROs=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "admin.myadmin", "userId" : UUID("374eebe5-8c05-445b-bf5c-0546b718736d"), "user" : "myadmin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "6lB27JXEHlEOFFNOJf0nIQ==", "storedKey" : "nY7hI/LcpSAOCrOqxIR438HZxsM=", "serverKey" : "hA4c8PWCzhgZDj2QO2VdZYm7upo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "3wnosLGfHWpsr6Co+TXEmMJ57CdYLKkFtBmRgw==", "storedKey" : "H4DV8vRTKtlOILWCuU26dsjZTzFxq+mACdCVFrh+r2g=", "serverKey" : "82TjOnSzVazOMp3HkhWzt1eGZTly0hLjn6g5eswsJl4=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
 #删除用户
> db.dropUser("myadmin")
true
> db.system.users.find()
{ "_id" : "admin.myroot", "userId" : UUID("de8dabd6-c2dc-4443-9e59-16f94940da60"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "/JAWRQVnNNHbWpWawFr6Iw==", "storedKey" : "qXwCwG9OiEoU9LlIm/lyEdq1iXg=", "serverKey" : "Tbfc9WjwnuwlxOidswV2m1qdxpQ=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "l95mqnLX3ipYn5PIHXCOMnMlFzeJGhD1YeUZ1Q==", "storedKey" : "RpQv9Kv2eulbBfANya4tB6SAyfC2RiFhAHrXyUem+vo=", "serverKey" : "fPGHqIU1t8wZGRaYdiNSKyBbypBwdAAocqS9lneRROs=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
#修改密码
> db.changeUserPassword("myroot", "123456")
> db.auth("myroot","12345")
Error: Authentication failed.
0
> db.auth("myroot","123456")
1
> use articledb
switched to db articledb
> db.createUser({user: "bobo", pwd: "123456", roles: [{ role: "readWrite", db:"articledb" }]})
Successfully added user: {
    "user" : "bobo",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "articledb"
        }
    ]
}
> db.auth("bobo","123456")
1
#修改服务器配置文件:vim /data/mongodb/conf/mongo.conf

systemLog:
  destination: file
  path: "/data/mongodb/log/mongodb.log"
  logAppend: true
storage:
  journal:
    enabled: true
  dbPath: "/data/mongodb/data/"
processManagement:
  fork: true
net:
  port: 27017
  bindIp: 192.168.100.86,127.0.0.1
security:
  authorization: enabled

[root@anolis8 ~]# systemctl start mongod  
[root@anolis8 ~]# systemctl status mongod  -l
● mongod.service - mongodb
   Loaded: loaded (/etc/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2023-01-10 10:50:18 CST; 9s ago
  Process: 302663 ExecStop=/data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf --shutdown (code=exited, status=0/SUCCESS)
  Process: 303018 ExecStart=/data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf (code=exited, status=0/SUCCESS)
 Main PID: 303020 (mongod)
    Tasks: 34 (limit: 24888)
   Memory: 155.9M
   CGroup: /system.slice/mongod.service
           └─303020 /data/mongodb/bin/mongod --config /data/mongodb/conf/mongo.conf

1月 10 10:50:16 anolis8 systemd[1]: Starting mongodb...
1月 10 10:50:16 anolis8 mongod[303018]: about to fork child process, waiting until server is ready for connections.
1月 10 10:50:16 anolis8 mongod[303018]: forked process: 303020
1月 10 10:50:18 anolis8 mongod[303018]: child process started successfully, parent exiting
1月 10 10:50:18 anolis8 systemd[1]: Started mongodb.
[root@anolis8 ~]# su mongod
[mongod@anolis8 root]$ mongo --port 27017
MongoDB shell version v4.4.18
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4f43e527-e826-4339-acb0-c38f0791d219") }
MongoDB server version: 4.4.18
> show dbs
> use admin
switched to db admin
> show collections
Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus
> db.system.users.find()
Error: error: {
    "ok" : 0,
    "errmsg" : "command find requires authentication",
    "code" : 13,
    "codeName" : "Unauthorized"
}
> db.auth("myroot","123456")
1
> db.system.users.find()
{ "_id" : "admin.myroot", "userId" : UUID("de8dabd6-c2dc-4443-9e59-16f94940da60"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "UYkxeop3DR6tUl1vW6i5Og==", "storedKey" : "qlspSn5g9/GB6p4Z97XDUkF2gBk=", "serverKey" : "sZ6GYpZyckfHejb4KnB1jOLftrg=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "s5NLDqiI3rMp+ra4n2grpiEq1IzWZI1OZNqmyw==", "storedKey" : "04dYUjV/Zn5OfIGavW52nQ5438fuydWIdR1yThDB/JU=", "serverKey" : "xZarJGo6xrvHree/36otzVqaeKbT3nnE8eei1OzgR64=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "articledb.bobo", "userId" : UUID("e9e6c363-2028-42e8-9424-fbc61f0d7c72"), "user" : "bobo", "db" : "articledb", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "DT/NEd2AXvY5YVlfwXBLEQ==", "storedKey" : "WUPI7b0ku+h/PFR6XEORCrhJAqI=", "serverKey" : "7alVMXfJuKAkxNywnU0J2FwDtSY=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "kLKaoMDft9nsQahkVtbf8CWpnPlvGYTQ3Kq0cw==", "storedKey" : "a4WDkAZ1MrGLpr78QDl79ivITTOwwQUuXJRPkgY6dTo=", "serverKey" : "jBZr6yk/wh0EK7An8BckyTL90drhEExyPk5cbcRNu9k=" } }, "roles" : [ { "role" : "readWrite", "db" : "articledb" } ] }
> show collections
system.users
system.version
> exit
-----------------------------------------------------------
[mongod@anolis8 root]$ mongo --port 27017
MongoDB shell version v4.4.18
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("bf5f49f9-f491-4bd4-964c-ca63594a9f2d") }
MongoDB server version: 4.4.18
> use articledb
switched to db articledb
> db.auth("bobo","123456")
1
> show collections
> show dbs

image.png

参考链接:https://www.jianshu.com/p/17044cb459eb

上一篇 下一篇

猜你喜欢

热点阅读