从python脚本获取mongod rs.status()结果

时间:2018-12-10 15:03:40

标签: python mongodb

出于监控目的,我尝试从python脚本获取以下shell命令的输出

:mongo --port 27040
-> enters mongodb shell
:rs.status()

查看图片 mongo command

命令的结果是我想在mongo shell外部访问的json以将其写入文件,我可以使用pymongo在python中运行其他命令,例如:

import json, os  
# load mongo library
current_dir = os.path.dirname(os.path.realpath(__file__))
os.sys.path.append(os.path.join(current_dir, 'pymongo-3.7.1-cp27-cp27m-manylinux1_x86_64.whl'))

from bson import json_util
from pymongo import MongoClient
from pymongo.errors import OperationFailure, ConnectionFailure

#connection settings
port = 27040
hostname = "localhost"
#default database used by mongodb
database = "test"

try:
    # connect to the database
    client = MongoClient(hostname,int(port))
    db = client[database] # select the database
    serverstats = db.command("serverStatus")
    serialized_serverstats = json.dumps(serverstats, default=json_util.default)
    print serialized_serverstats
except Exception as e:
    print("Unhandled Error is %s" % e)

这相当于在mongo shell中运行db.serverStatus()。 但是,如何在python脚本中运行rs.status()表单?

1 个答案:

答案 0 :(得分:1)

您应该这样做:

db = client ['admin']
db_stats = db.command({'replSetGetStatus'  :1})

如果要检查任何shell命令的基础命令是什么

> rs.status
function () {
    return db._adminCommand("replSetGetStatus");
}
>