how to get connected clients in MongoDB

前端 未结 3 1968
误落风尘
误落风尘 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

    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
    

提交回复
热议问题