美文网首页
06-MongoDB集群运维-访问权限

06-MongoDB集群运维-访问权限

作者: 过桥 | 来源:发表于2019-10-24 17:07 被阅读0次

    添加用户访问权限

    添加管理员

    database_repl:PRIMARY> use admin
    switched to db admin
    database_repl:PRIMARY> db.createUser({
    ...     user: "sa",
    ...     pwd: "sa_coin",
    ...     roles: [{ role: "root", db: "admin" }]
    ... });
    Successfully added user: {
        "user" : "sa",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ]
    }
    database_repl:PRIMARY> 
    

    添加普通用户

    database_repl:PRIMARY> use test
    switched to db test
    database_repl:PRIMARY> db.createUser({user:'dev',pwd:'123456',roles:[{role:'dbOwner',db:'test'}]})  
    Successfully added user: {
        "user" : "dev",
        "roles" : [
            {
                "role" : "dbOwner",
                "db" : "test"
            }
        ]
    }
    database_repl:PRIMARY> 
    

    注:添加用户操作,主节点操作即可,集群自动同步其他节点

    问题一、当前操作不是主节点,切换至主节点操作
    database_repl:SECONDARY> use admin
    switched to db admin
    database_repl:SECONDARY> db.createUser({
    ...     user: "root",
    ...     pwd: "root_coin",
    ...     roles: [{ role: "root", db: "admin" }]
    ... });
    2019-10-24T15:22:41.336+0800 E  QUERY    [js] uncaught exception: Error: couldn't add user: not master :
    _getErrorWithCode@src/mongo/shell/utils.js:25:13
    DB.prototype.createUser@src/mongo/shell/db.js:1370:11
    @(shell):1:1
    
    
    问题二、用户已存在,修改用户名
    database_repl:PRIMARY> use admin
    switched to db admin
    database_repl:PRIMARY> db.createUser({
    ...     user: "root",
    ...     pwd: "root_coin",
    ...     roles: [{ role: "root", db: "admin" }]
    ... });
    2019-10-24T15:26:30.166+0800 E  QUERY    [js] uncaught exception: Error: couldn't add user: User "root@admin" already exists :
    _getErrorWithCode@src/mongo/shell/utils.js:25:13
    DB.prototype.createUser@src/mongo/shell/db.js:1370:11
    @(shell):1:1
    database_repl:PRIMARY>
    

    创建副本集认证key文件并拷贝至其他节点

    [mongodb@mongodb01 mongo]$ sudo openssl rand -base64 90 -out ./mongodb-keyfile
    [mongodb@mongodb01 mongo]$ sudo chmod 300 mongodb-keyfile 
    
    [mongodb@mongodb01 mongo]$ scp /opt/mongo/mongodb-keyfile mongodb@192.168.153.129:/opt/mongo/mongodb-keyfile
    mongodb@192.168.153.129's password: 
    /opt/mongo/mongodb-keyfile: Permission denied
    
    [mongodb@mongodb01 mongo]$ sudo scp /opt/mongo/mongodb-keyfile root@192.168.153.129:/opt/mongo/mongodb-keyfile
    root@192.168.153.129's password: 
    mongodb-keyfile                                                                                                                                                                                                100%  122    11.3KB/s   00:00    
    [mongodb@mongodb01 mongo]$ 
    
    

    分别重启集群中数据库服务

    开启权限配置,重启服务
    [mongodb@mongodb01 bin]$ sudo vim /opt/mongo/mongo.conf
    
    fork=true
    dbpath=/opt/mongo/data/db
    port=27017
    bind_ip=0.0.0.0
    logpath=/opt/mongo/logs/mongodb.log
    logappend=true
    replSet=database_repl
    auth=true #添加此行
    keyFile=/opt/mongo/mongodb-keyfile  #添加此行
    
    [mongodb@mongodb01 bin]$ 
    
    重启服务
    [mongodb@mongodb03 bin]$ sudo netstat -ntlp
    Active Internet connections (only servers)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
    tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      85296/./mongod      
    
    [mongodb@mongodb03 bin]$ sudo kill -9 85296
    [mongodb@mongodb03 bin]$ sudo ./mongod --config /opt/mongo/mongo.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 85714
    child process started successfully, parent exiting
    [mongodb@mongodb03 bin]$ 
    

    测试权限是否添加成功

    测试方法一

    进入mongo管理

    database_repl:PRIMARY> use test
    switched to db test
    database_repl:PRIMARY> db.auth("dev","123456")
    1
    database_repl:PRIMARY> db.auth("dev","1234567")
    Error: Authentication failed.
    0
    
    测试方法二

    进入mongo管理,执行rs.status()失败

    [mongodb@mongodb03 bin]$ ./mongo
    MongoDB shell version v4.2.1
    connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("54118c3b-a28e-4253-b6a9-63f30423d77e") }
    MongoDB server version: 4.2.1
    
    database_repl:SECONDARY> rs.status();
    {
        "operationTime" : Timestamp(1571903408, 1),
        "ok" : 0,
        "errmsg" : "command replSetGetStatus requires authentication",
        "code" : 13,
        "codeName" : "Unauthorized",
        "$clusterTime" : {
            "clusterTime" : Timestamp(1571903408, 1),
            "signature" : {
                "hash" : BinData(0,"7Isfr3c54Eqbkx/EH6vhJYYEwWw="),
                "keyId" : NumberLong("6749416899504766978")
            }
        }
    }
    
    测试方法三

    命令链接./mongo -u 用户名 -p 密码

    [mongodb@mongodb02 bin]$ ./mongo -u dev -p dev1
    MongoDB shell version v4.2.1
    connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
    2019-10-24T17:50:27.184+0800 E  QUERY    [js] Error: Authentication failed. :
    connect@src/mongo/shell/mongo.js:341:17
    @(connect):2:6
    2019-10-24T17:50:27.210+0800 F  -        [main] exception: connect failed
    2019-10-24T17:50:27.210+0800 E  -        [main] exiting with code 1
    
    [mongodb@mongodb02 bin]$ ./mongo -u sa -p sa_coin
    MongoDB shell version v4.2.1
    connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
    Implicit session: session { "id" : UUID("47dea6c2-bc9f-4dc6-af63-6e0e4ebfc508") }
    MongoDB server version: 4.2.1
    Server has startup warnings: 
    2019-10-24T16:39:26.124+0800 I  CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
    2019-10-24T16:39:26.124+0800 I  CONTROL  [initandlisten] 
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] 
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] 
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
    2019-10-24T16:39:26.125+0800 I  CONTROL  [initandlisten] 
    ---
    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()
    ---
    
    database_repl:RECOVERING> 
    
    
    测试方法四

    Python代码链接

    #! /usr/bin/env python
    #coding=utf-8
    
    import time, os 
    import datetime
    from pymongo import MongoClient
    from pymongo import ReadPreference
    # 数据备份至 mongo,需先安装 pymongo
    # pip install pymongo
    
    #MongoDB 数据库链接
    conn = MongoClient(['192.168.153.128:27017', '192.168.153.129:27017', '192.168.153.130:27017'])
    
    db = conn.get_database('test', read_preference=ReadPreference.SECONDARY_PREFERRED)
    
    db.authenticate("dev", "123456")
    
    # db.products.insert({"name": "py_insert", "age": 123})
    
    x = db.products.find_one()
     
    print(x)
    

    相关文章

      网友评论

          本文标题:06-MongoDB集群运维-访问权限

          本文链接:https://www.haomeiwen.com/subject/kqedvctx.html