温馨提示×

centos mongodb怎样免密

小樊
37
2026-09-30 00:54:07
栏目: 云计算

在 CentOS 上让 MongoDB 免密登录(无密码访问),常见有几种方式,按使用场景说明:


一、完全关闭 MongoDB 鉴权(最简单,仅测试/内网可用)

1. 修改配置文件

vi /etc/mongod.conf

找到 security 部分,确保 没有 以下内容:

security:
  authorization: enabled

或者直接写成:

security:
  authorization: disabled

2. 重启 MongoDB

systemctl restart mongod

3. 直接连接(无需密码)

mongo
# 或
mongosh

✅ 此时 无任何账号密码校验

⚠️ 风险:任何人都能访问,公网绝对不要用


二、本地 socket 免密(推荐生产环境)

MongoDB 默认允许 本机通过 localhost 免密管理

只要:

  • 没开 authorization
  • 或你是 root / 本地管理员
mongo

适用于:

  • 脚本
  • 运维管理

三、指定用户但免交互输入密码(运维常用)

1. 创建用户

use admin
db.createUser({
  user: "admin",
  pwd: "123456",
  roles: ["root"]
})

2. 开启鉴权

security:
  authorization: enabled

3. 使用密码文件免交互

echo "123456" > /etc/mongo_pass
chmod 600 /etc/mongo_pass

连接:

mongo -u admin -p $(cat /etc/mongo_pass) --authenticationDatabase admin

或 MongoDB 6+:

mongosh -u admin -p $(cat /etc/mongo_pass) --authenticationDatabase admin

四、使用 keyFile(集群常用)

适合 副本集 / 分片

security:
  authorization: enabled
  keyFile: /etc/mongo-keyfile
openssl rand -base64 756 > /etc/mongo-keyfile
chmod 600 /etc/mongo-keyfile

五、总结建议

场景 推荐方式
本地测试 关闭 authorization
生产单机 本地 localhost 管理
脚本自动 密码文件
集群 keyFile

如果你能说明:

  • MongoDB 版本
  • 单机 / 集群
  • 是否公网

我可以给你 最安全的具体配置示例。

0 踩