MongoDB显示当前用户 [英] MongoDB Show Current User

查看:1717
本文介绍了MongoDB显示当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示当前用户登录到mongo shell的身份?知道这一点很有用,因为可以更改您登录的用户的身份,例如. db.auth("newuser", "password")—在交互式外壳中.一个人很容易迷路.

How do I show the current user that I'm logged into the mongo shell as? This is useful to know because it is possible to change the user that you are logged in as—e.g. db.auth("newuser", "password")—while in the interactive shell. One can easily lose track.

使用接受的答案作为基础,我将提示更改为包括用户,连接和数据库:

Using the accepted answer as a base, I changed the prompt to include user, connection, and db:

在您的主目录中编辑.mongorc.js.

function prompt() {
    var username = "anon";
    var user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0];
    var host = db.getMongo().toString().split(" ")[2];
    var current_db = db.getName();

    if (!!user) {
        username = user.user;
    }

    return username + "@" + host + ":" + current_db + "> ";
}

结果:

MongoDB shell version: 2.4.8
connecting to: test

anon@127.0.0.1:test> use admin
switched to db admin

anon@127.0.0.1:admin> db.auth("a_user", "a_password")
1

a_user@127.0.0.1:admin>

推荐答案

connectionStatus命令显示经过身份验证的用户(如果有的话,以及其他一些数据):

The connectionStatus command shows authenticated users (if any, among some other data):

db.runCommand({connectionStatus : 1})

这会导致类似波纹管的事情:

Which results in something like bellow:

{
    "authInfo" : {
            "authenticatedUsers" : [
                    {
                            "user" : "aa",
                            "userSource" : "test"
                    }
            ]
    },
    "ok" : 1
}

因此,如果您从外壳连接,则基本上是当前用户

So if you are connecting from the shell, this is basically the current user

您还可以通过覆盖OS用户主目录下.mongorc.js文件中的prompt函数来添加用户名以进行提示.大致:

You can also add the user name to prompt by overriding the prompt function in .mongorc.js file, under OS user home directory. Roughly:

prompt = function() {
    user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0]
    if (user) {
        return "user: " + user.user + ">"
    }
    return ">"
}       

一个例子:

$ mongo -u "cc" -p "dd"
MongoDB shell version: 2.4.8
connecting to: test
user: cc>db.auth("aa", "bb")
1
user: aa>

这篇关于MongoDB显示当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆