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,是因为 ...
随机推荐
- Android之线程安全的单例模式,Adapter注意事项之引用传值
线程安全的单例模式单位模式一般写法如下: public static FestivalLab mInstance; private FestivalLab() { } public static Fe ...
- 小程序如何去掉button组件的边框
小程序获取用户授权不再支持wx.getUserInfo方法,改为用button获取,格式如下 <button class="btn btn" open-type=" ...
- 了解url
我对自己知道关于url的编码和解码的一些进行了一下整理. 我们的例子是百度翻译的地址: http://fanyi.baidu.com/translate#en/zh/The%20%22%3F%20ar ...
- Kotlin操作符重载:把标准操作加入到任何类中(KAD 17)
作者:Antonio Leiva 时间:Mar 21, 2017 原文链接:https://antonioleiva.com/operator-overload-kotlin/ 就像其他每种语言一样, ...
- Java中的while(true)
while(true)是一个无限循环 在内部用break或return退出循环,否则一直循环
- iOS-技术细节整理
遇到未使用类,可以看看xcode->help->developer documentation 下面做一下简单的技术细节整理 Auto Layout使用Auto Layout来灵活改变UI ...
- HDU 4782 Beautiful Soup (模拟+注意细节)
思路就是用栈模拟,不用开实体的栈,直接记一个top指针就行. 说说这题的细节: 1.tag标签里的内容不要动,原样输出.比如<p aa bb cc>,就这样输出就行,不要删空格.题目中说了 ...
- B - 寻找M
B - 寻找M Time Limit: 1000/1000MS (C++/Others) Memory Limit: 65536/65536KB (C++/Others) Problem Descri ...
- Struts1防止表单重复提交
package org.zln.struts.action; import org.apache.struts.action.Action; import org.apache.struts.acti ...
- hdu 1249 三角形 (递推)
三角形 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...