博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mongodb安全
阅读量:5299 次
发布时间:2019-06-14

本文共 20233 字,大约阅读时间需要 67 分钟。

 1.流程:

  (1)创建超级管理员

  (2)修改配置文件,验证身份登录

  (3)重启服务

  (4)使用超级管理员登录

  (5)创建普通用户

  (6)使用普通用户登录对应的数据库

 

 

 

 

mongodb数据库角色:

 

 

1创建用户:(只要指明角色和授予的数据库)

 

创建用户:(注意切换到admin数据库:)

> use adminswitched to db admin> db.createUser({
"user":"root",pwd:"123456",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-64-3.6.3\binmongod.exe --auth --dbpath c:\data\dbpause

 

 

 3.登录数据库:(需要制定数据库和密码)

 直接登录:

mongo -u root -p 123456 --authenticationDatabase admin

 

  这是以管理员身份登录,登录之后可以对任何数据库进行操作

 

因此将上面命令也可以写成一个脚本:

e:cd E:\mongodb\mongodb-win32-x86_64-enterprise-windows-64-3.6.3\binmongod.exe --auth --dbpath c:\data\dbpause

 

 

 

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.3connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.6.32018-03-26T22:32:07.191+0800 E QUERY    [thread1] Error: Authentication failed.:DB.prototype._authOrThrow@src/mongo/shell/db.js:1608:20@(auth):6:1@(auth):1:2exception: login failedC:\Users\liqiang>mongo -u user -p user --authenticationDatabase mydb  #普通用户登录分配给他的mydb数据库正常MongoDB shell version v3.6.3connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.6.3

 

 

 

MongoDB Enterprise > dbadminMongoDB Enterprise > use mydb  #访问admin数据库报错switched to db mydbMongoDB Enterprise > show tables   #访问mydb正常mydbMongoDB 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 - 27017 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 (=2147483647)     set socket listen backlog size  --maxConns arg                        max number of simultaneous connections                                        - 1000000 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 (=100)                   value of slow for profile and console                                        log  --slowOpSampleRate arg (=1)           fraction of slow ops to include in the                                        profile and console log  --profile arg                         0=off 1=slow, 2=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 scansWindows 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                                        serviceUserReplication options:  --oplogSize arg                       size to use (in MB) for replication op                                        log. default is 5% 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                                        
--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 staleReplica set options: --replSet arg arg is
[/
] --replIndexPrefetch arg specify index prefetching behavior (if secondary) [none|_id_only|all] --enableMajorityReadConcern [=arg(=1)] (=1) enables majority readConcernSharding options: --configsvr declare this is a config db of a cluster; default port 27019; default dir /data/configdb --shardsvr declare this is a shard db of a cluster; default port 27018SSL 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 140-2 mode at startupStorage 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 (=16) .ns file size (in MB) for new databases --quota limits each database to a certain number of files (8 default) --quotaFiles arg number of files allowed per db, implies --quota --smallfiles use a smaller default file size --syncdelay arg (=60) seconds between disk syncs (0=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 64 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 recordsKerberos 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 masterEncryption 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 5696) --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 serverLDAP 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 (=10000) 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 usernameWiredTiger options: --wiredTigerCacheSizeGB arg maximum amount of memory to allocate for cache; defaults to 1/2 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 (=1) use prefix compression on row-store leaf pagesInMemory options: --inMemorySizeGB arg maximum amount of memory to allocate for InMemory data; defaults to 50% of physical RAM less 1GB

 

 

附一些mongo的参数:

C:\Users\liqiang>mongo -helpMongoDB shell version v3.6.3usage: 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:9999/foo  foo database on 192.168.0.5 machine on port 9999Options:  --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 140-2 mode at startup  --retryWrites                         automatically retry write operations                                        upon transient network errors  --jsHeapLimitMB arg                   set the js scope's heap size limitAuthentication 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 authenticationKerberos 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

 

转载于:https://www.cnblogs.com/qlqwjy/p/8654577.html

你可能感兴趣的文章
Python-S9-Day127-Scrapy爬虫框架2
查看>>
SecureCRT的使用方法和技巧(详细使用教程)
查看>>
右侧导航栏(动态添加数据到list)
查看>>
81、iOS本地推送与远程推送详解
查看>>
虚拟DOM
查看>>
uva 11468 Substring
查看>>
自建数据源(RSO2)、及数据源增强
查看>>
BootStrap2学习日记2--将固定布局换成响应式布局
查看>>
关于View控件中的Context选择
查看>>
2018icpc徐州OnlineA Hard to prepare
查看>>
Spark的启动进程详解
查看>>
使用命令创建数据库和表
查看>>
数据库的高级查询
查看>>
机器视觉:SSD Single Shot MultiBox Detector
查看>>
201521123044 《Java程序设计》第1周学习总结
查看>>
MIT Scheme 的基本使用
查看>>
程序员的“机械同感”
查看>>
在16aspx.com上下了一个简单商品房销售系统源码,怎么修改它的默认登录名和密码...
查看>>
c++回调函数
查看>>
linux下Rtree的安装
查看>>