mongodb安全
1.流程:
(1)创建超级管理员
(2)修改配置文件,验证身份登录
(3)重启服务
(4)使用超级管理员登录
(5)创建普通用户
(6)使用普通用户登录对应的数据库
mongodb数据库角色:
1创建用户:(只要指明角色和授予的数据库)
创建用户:(注意切换到admin数据库:)
> use admin
switched to db admin
> db.createUser({"user":"root",pwd:"",roles:[{role:"root",db:"admin"}]})
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
2.修改配置文件,启动验证身份:
- linux下面修改/etc/mongod.conf (注意后面有空格)
重启服务即可
- windows下面: 在启动mongod的时候后面携带--auth 参数,其中参数有很多,在最后会附上启动参数。
mongod --auth
如果需要制定数据路径:
mongod --auth --dbpath c:\data\db
因此可以将上面命令写入一bat脚本。(前提是将mongod的目录配置到环境变量path)
例如我的一个bat脚本:(我的安装目录是E:\mongodb\mongodb-win32-x86_64-enterprise-windows-64-3.6.3\bin)
e:
cd E:\mongodb\mongodb-win32-x86_64-enterprise-windows--3.6.\bin
mongod.exe --auth --dbpath c:\data\db
pause
3.登录数据库:(需要制定数据库和密码)
直接登录:
mongo -u root -p --authenticationDatabase admin
这是以管理员身份登录,登录之后可以对任何数据库进行操作
因此将上面命令也可以写成一个脚本:
e:
cd E:\mongodb\mongodb-win32-x86_64-enterprise-windows--3.6.\bin
mongod.exe --auth --dbpath c:\data\db
pause
4.实际开发中是超级管理员创建一普通账户并给其分配对应的数据库,因此此用户只能操作其对应的数据库
- 创建普通用户(对mydb数据库具有读写权限,账号密码都是user)
db.createUser({
"user":"user",
"pwd":"user",
roles:[{
"role":"readWrite",
"db":"mydb"
}]
})
- 重启服务之后测试:
C:\Users\liqiang>mongo -u user -p user --authenticationDatabase admin #普通用户登录admin数据库报错
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.
--26T22::07.191+ E QUERY [thread1] Error: Authentication failed.
:
DB.prototype._authOrThrow@src/mongo/shell/db.js::
@(auth)::
@(auth)::
exception: login failed C:\Users\liqiang>mongo -u user -p user --authenticationDatabase mydb #普通用户登录分配给他的mydb数据库正常
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.
MongoDB Enterprise > db
admin
MongoDB Enterprise > use mydb #访问admin数据库报错
switched to db mydb
MongoDB Enterprise > show tables #访问mydb正常
mydb
MongoDB Enterprise >
附一些mongod启动参数:
C:\Users\liqiang>mongod/?
Invalid command: /?
Options: General options:
-h [ --help ] show this usage information
--version show version information
-f [ --config ] arg configuration file specifying
additional options
-v [ --verbose ] [=arg(=v)] be more verbose (include multiple times
for more verbosity e.g. -vvvvv)
--quiet quieter output
--port arg specify port number - by default
--bind_ip arg comma separated list of ip addresses to
listen on - localhost by default
--bind_ip_all bind to all ip addresses
--ipv6 enable IPv6 support (disabled by
default)
--listenBacklog arg (=) set socket listen backlog size
--maxConns arg max number of simultaneous connections
- by default
--logpath arg log file to send write to instead of
stdout - has to be a file, not
directory
--logappend append to logpath instead of
over-writing
--logRotate arg set the log rotation behavior
(rename|reopen)
--timeStampFormat arg Desired format for timestamps in log
messages. One of ctime, iso8601-utc or
iso8601-local
--redactClientLogData Redact client data written to the
diagnostics log
--pidfilepath arg full path to pidfile (if not set, no
pidfile is created)
--timeZoneInfo arg full path to time zone info directory,
e.g. /usr/share/zoneinfo
--keyFile arg private key for cluster authentication
--noauth run without security
--setParameter arg Set a configurable parameter
--transitionToAuth For rolling access control upgrade.
Attempt to authenticate over outgoing
connections and proceed regardless of
success. Accept incoming connections
with or without authentication.
--clusterAuthMode arg Authentication mode used for cluster
authentication. Alternatives are
(keyFile|sendKeyFile|sendX509|x509)
--networkMessageCompressors [=arg(=disabled)] (=snappy)
Comma-separated list of compressors to
use for network messages
--auth run with security
--clusterIpSourceWhitelist arg Network CIDR specification of permitted
origin for `__system` access.
--slowms arg (=) value of slow for profile and console
log
--slowOpSampleRate arg (=) fraction of slow ops to include in the
profile and console log
--profile arg =off =slow, =all
--cpu periodically show cpu and iowait
utilization
--sysinfo print some diagnostic system
information
--noIndexBuildRetry don't retry any index builds that were
interrupted by shutdown
--noscripting disable scripting engine
--notablescan do not allow table scans Windows Service Control Manager options:
--install install Windows service
--remove remove Windows service
--reinstall reinstall Windows service (equivalent
to --remove followed by --install)
--serviceName arg Windows service name
--serviceDisplayName arg Windows service display name
--serviceDescription arg Windows service description
--serviceUser arg account for service execution
--servicePassword arg password used to authenticate
serviceUser Replication options:
--oplogSize arg size to use (in MB) for replication op
log. default is % of disk space (i.e.
large is good) Master/slave options (old; use replica sets instead):
--master master mode
--slave slave mode
--source arg when slave: specify master as
<server:port>
--only arg when slave: specify a single database
to replicate
--slavedelay arg specify delay (in seconds) to be used
when applying master ops to slave
--autoresync automatically resync if slave data is
stale Replica set options:
--replSet arg arg is <setname>[/<optionalseedhostlist
>]
--replIndexPrefetch arg specify index prefetching behavior (if
secondary) [none|_id_only|all]
--enableMajorityReadConcern [=arg(=)] (=)
enables majority readConcern Sharding options:
--configsvr declare this is a config db of a
cluster; default port ; default
dir /data/configdb
--shardsvr declare this is a shard db of a
cluster; default port SSL options:
--sslOnNormalPorts use ssl on configured ports
--sslMode arg set the SSL operation mode
(disabled|allowSSL|preferSSL|requireSSL
)
--sslPEMKeyFile arg PEM file for ssl
--sslPEMKeyPassword arg PEM file password
--sslClusterFile arg Key file for internal SSL
authentication
--sslClusterPassword arg Internal authentication key file
password
--sslCAFile arg Certificate Authority file for SSL
--sslCRLFile arg Certificate Revocation List file for
SSL
--sslDisabledProtocols arg Comma separated list of TLS protocols
to disable [TLS1_0,TLS1_1,TLS1_2]
--sslWeakCertificateValidation allow client to connect without
presenting a certificate
--sslAllowConnectionsWithoutCertificates
allow client to connect without
presenting a certificate
--sslAllowInvalidHostnames Allow server certificates to provide
non-matching hostnames
--sslAllowInvalidCertificates allow connections to servers with
invalid certificates
--sslFIPSMode activate FIPS - mode at startup Storage options:
--storageEngine arg what storage engine to use - defaults
to wiredTiger if no data files present
--dbpath arg directory for datafiles - defaults to
\data\db\ which is C:\data\db\ based on
the current working drive
--directoryperdb each database will be stored in a
separate directory
--noprealloc disable data file preallocation - will
often hurt performance
--nssize arg (=) .ns file size (in MB) for new databases
--quota limits each database to a certain
number of files ( default)
--quotaFiles arg number of files allowed per db, implies
--quota
--smallfiles use a smaller default file size
--syncdelay arg (=) seconds between disk syncs (=never,
but not recommended)
--upgrade upgrade db if needed
--repair run repair on all dbs
--repairpath arg root directory for repair files -
defaults to dbpath
--journal enable journaling
--nojournal disable journaling (journaling is on by
default for bit)
--journalOptions arg journal diagnostic options
--journalCommitInterval arg how often to group/batch commit (ms) Auditing Options:
--auditDestination arg Destination of audit log output.
(console/syslog/file)
--auditFormat arg Format of the audit log, if logging to
a file. (BSON/JSON)
--auditPath arg full filespec for audit log file
--auditFilter arg filter spec to screen audit records Kerberos Options:
--sspiHostnameCanonicalization arg (=none)
DNS resolution strategy to use for
hostname canonicalization. May be one
of: {none, forward, forwardAndReverse} SNMP Module Options:
--snmp-subagent run snmp subagent
--snmp-master run snmp as master Encryption at rest options:
--enableEncryption Enable encryption at rest
--encryptionKeyFile arg File path for encryption key file
--encryptionCipherMode arg Cipher mode to use for encryption at
rest
--kmipRotateMasterKey Rotate master encryption key
--kmipKeyIdentifier arg KMIP unique identifier for existing key
to use
--kmipServerName arg KMIP server host name
--kmipPort arg KMIP server port (defaults to )
--kmipClientCertificateFile arg Client certificate for authenticating
to KMIP server
--kmipClientCertificatePassword arg Client certificate for authenticating
Mongo to KMIP server
--kmipServerCAFile arg CA File for validating connection to
KMIP server LDAP Module Options:
--ldapServers arg Comma separated list of LDAP servers on
format host:port
--ldapTransportSecurity arg (=tls) Transport security used between MongoDB
and remote LDAP server(none|tls)
--ldapBindWithOSDefaults Peform queries with the service
account's username and password
--ldapBindMethod arg (=simple) Authentication scheme to use while
connecting to LDAP. This may either be
'sasl' or 'simple'
--ldapBindSaslMechanisms arg (=DIGEST-MD5)
Comma separated list of SASL mechanisms
to use while binding to the LDAP server
--ldapTimeoutMS arg (=) Timeout for LDAP queries (ms)
--ldapQueryUser arg LDAP entity to bind with to perform
queries
--ldapQueryPassword arg Password to use while binding to the
LDAP server to perform queries
--ldapUserToDNMapping arg (=[{match: "(.+)", substitution: "{0}"}])
Tranformation from MongoDB users to
LDAP user DNs
--ldapAuthzQueryTemplate arg Relative LDAP query URL which will be
queried against the host to acquire
LDAP groups. The token {USER} will be
replaced with the mapped username WiredTiger options:
--wiredTigerCacheSizeGB arg maximum amount of memory to allocate
for cache; defaults to / of physical
RAM
--wiredTigerJournalCompressor arg (=snappy)
use a compressor for log records
[none|snappy|zlib]
--wiredTigerDirectoryForIndexes Put indexes and data in different
directories
--wiredTigerCollectionBlockCompressor arg (=snappy)
block compression algorithm for
collection data [none|snappy|zlib]
--wiredTigerIndexPrefixCompression arg (=)
use prefix compression on row-store
leaf pages InMemory options:
--inMemorySizeGB arg maximum amount of memory to allocate
for InMemory data; defaults to % of
physical RAM less 1GB
附一些mongo的参数:
C:\Users\liqiang>mongo -help
MongoDB shell version v3.6.3
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.168.0.5/foo foo database on 192.168.0.5 machine
192.168.0.5:/foo foo database on 192.168.0.5 machine on port
Options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by
default)
--disableJavaScriptJIT disable the Javascript Just In Time
compiler
--disableJavaScriptProtection allow automatic JavaScript function
marshalling
--ssl use SSL for all connections
--sslCAFile arg Certificate Authority file for SSL
--sslPEMKeyFile arg PEM certificate/key file for SSL
--sslPEMKeyPassword arg password for key in PEM file for SSL
--sslCRLFile arg Certificate Revocation List file for
SSL
--sslAllowInvalidHostnames allow connections to servers with
non-matching hostnames
--sslAllowInvalidCertificates allow connections to servers with
invalid certificates
--sslFIPSMode activate FIPS - mode at startup
--retryWrites automatically retry write operations
upon transient network errors
--jsHeapLimitMB arg set the js scope's heap size limit Authentication Options:
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg authentication mechanism
--gssapiServiceName arg (=mongodb) Service name to use when authenticating
using GSSAPI/Kerberos
--gssapiHostName arg Remote host name to use for purpose of
GSSAPI/Kerberos authentication Kerberos Options:
--sspiHostnameCanonicalization arg (=none)
DNS resolution strategy to use for
hostname canonicalization. May be one
of: {none, forward, forwardAndReverse} file names: a list of files to run. files have to end in .js and will exit after
unless --shell is specified
mongodb安全的更多相关文章
- 【翻译】MongoDB指南/聚合——聚合管道
[原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...
- 【翻译】MongoDB指南/CRUD操作(四)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...
- 【翻译】MongoDB指南/CRUD操作(三)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...
- 【翻译】MongoDB指南/CRUD操作(二)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...
- 【翻译】MongoDB指南/CRUD操作(一)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...
- CRL快速开发框架系列教程十二(MongoDB支持)
本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...
- MongoDB系列(二):C#应用
前言 上一篇文章<MongoDB系列(一):简介及安装>已经介绍了MongoDB以及其在window环境下的安装,这篇文章主要讲讲如何用C#来与MongoDB进行通讯.再次强调一下,我使用 ...
- MongoDB系列(一):简介及安装
什么是MongoDB MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为应用提供可扩展的高 ...
- [原]分享一下我和MongoDB与Redis那些事
缘起:来自于我在近期一个项目上遇到的问题,在Segmentfault上发表了提问 知识背景: 对不是很熟悉MongoDB和Redis的同学做一下介绍. 1.MongoDB数组查询:MongoDB自带L ...
- 用MongoDB分析合肥餐饮业
看了<从数据角度解析福州美食>后难免心痒,动了要分析合肥餐饮业的念头,因此特地写了Node.js爬虫爬取了合肥的大众点评数据.分析数据库我并没有采用MySQL而是用的MongoDB,是因为 ...
随机推荐
- Python 3基础教程23-多维列表
这里简单举例一个多维列表,多维看起来都很晕. # 多维列表 x = [ [5,6],[6,7],[7,2] ,[2,5] ,[4,9]] print(x) # 根据索引引用列表元素,例如打印[6,7] ...
- Ubuntu16.04安装Zabbix
基于Zabbix+MySQL+Apache(可选) apt-get install php7.0-bcmath php7.0-xml php7.0-mbstring安装Zabbix所需的几个PHP模块 ...
- 扩展欧几里得 求ax+by == n的非负整数解个数
求解形如ax+by == n (a,b已知)的方程的非负整数解个数时,需要用到扩展欧几里得定理,先求出最小的x的值,然后通过处理剩下的区间长度即可得到答案. 放出模板: ll gcd(ll a, ll ...
- 合规P2P平台成PE/VC新宠
013年是互联网金融元年,余额宝.百发等掀起了大众理财的新一轮高潮.P2P平台作为互联网金融模式之一,也受到市场的重点关注-在部分平台不断爆出风险事件的同时,业内较为成熟的平台也正成为PE/VC的新宠 ...
- 信号处理是Unix和LInux系统为了响应某些状况而产生的事件
信号处理是Unix和LInux系统为了响应某些状况而产生的事件,通常内核产生信号,进程收到信号后采取相应的动作. 例如当我们想强制结束一个程序的时候,我们通常会给它发送一个信号,然后该进程会捕捉到信号 ...
- PHP Warning: File upload error - unable to create a temporary file in Unknown on line 0
代码在本地运行一切都OK,放到服务器上,网站访问正常,上传就出现该错误. 提示:PHP Warning: File upload error - unable to create a temporar ...
- 树莓派搭建 Hexo 博客(二)
Hexo 一个开源的博客框架,本文记录了一下在树莓派上搭建 Hexo 博客的过程. 上一篇介绍了 Hexo 的配置,现在网站已经能在本地访问了,也能通过 hexo generate 命令生成静态界面 ...
- Pro Git - 笔记2
Git Basics Getting a Git Repository Initializing a Repository in an Existing Directory For Linux: $ ...
- JavaSE复习(七)Stream流和方法引用
Stream流 全新的Stream概念,用于解决已有集合类库既有的弊端. 传统集合的多步遍历代码 几乎所有的集合(如 Collection 接口或 Map 接口等)都支持直接或间接的遍历操作.而当我们 ...
- lintcode-62-搜索旋转排序数组
62-搜索旋转排序数组 假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2).给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引 ...