how to get connected clients in MongoDB

前端 未结 3 1969
误落风尘
误落风尘 2021-02-05 15:15

I\'m writing an app using mongo as its db. I want to print the clients connected to the db, for example, print their ip. How can I get that info?

I tried using

相关标签:
3条回答
  • 2021-02-05 16:01

    You should be able to run this command and get a list of connected IP addresses:

    db.currentOp(true).inprog.forEach(function(d){if (d.client)printjson(d.client)})
    

    db.currentOp is actually built on top of the special collection $cmd.sys.inprog so you can also query that directly. You can get an idea of the how to do that by typing in db.currentOp without the parentheses into the mongo shell and it will print out the source for the function:

    > db.currentOp
    function ( arg ){
        var q = {}
        if ( arg ) {
            if ( typeof( arg ) == "object" )
                Object.extend( q , arg );
            else if ( arg )
                q["$all"] = true;
        }
        return this.$cmd.sys.inprog.findOne( q );
    }
    
    0 讨论(0)
  • 2021-02-05 16:01

    This is a bit hacky, but you can actually get this via netstat, even without connecting to the db. This would be done in a (bash) shell script on the DB server. I actually have this in my login script (~/.bash_profile), so that I can easily (& quickly) find network connections into MongoDB and any other service that runs on TCP.

    First, you would run this in the shell, which defines a function.

    function whoIsConnectedToPort () {
        PORT=$1
        netstat -an | grep ":${PORT}.*ESTAB" | awk '{print $4":"$5}' | cut -d: -f2- | grep "^${PORT}:" | cut -d: -f2 | grep -v '^127' | sort | uniq | xargs -n1 nslookup | grep 'name =' | awk {'print $NF'} | sed 's/.$//' | sort | uniq
    }
    

    Then invoke the function.

    whoIsConnectedToPort 27017
    

    This should return a list of hosts connected to the given port.

    You can reuse it for other familiar ports. Try for example:

    whoIsConnectedToPort 22
    whoIsConnectedToPort 3306
    whoIsConnectedToPort 1521
    
    0 讨论(0)
  • 2021-02-05 16:15

    You can use db.currentOp(true) and iterate over the inprog array of the result set, using the client field.

    0 讨论(0)
提交回复
热议问题