简单的mongo小工具 python

#!/bin/python
#coding=utf-8
### eg : mgotool.py  -i 127.0.0.1 -p 10001 -a xxxxx -u root -rc
#import sys
#sys.path.append('../')
#reload(sys)
#import MySQLdb
#import redis
import datetime
import pymongo
import argparse
import commands
import os,sys,glob,re,time
import ConfigParser
from tempfile import TemporaryFile
class mymongo:
    host=None
    port=None
    passwd=None
    user=None

    def __init__(self,host,port,user,passwd,dbname):
        self.host=host
        self.port=port
        self.passwd=passwd
        self.user=user
        self.dbname=dbname
        try:
            self.conn=self.mongo_conn()
            self.succ=True
        except Exception as error:
            print error
            print  "Connect mongo error: %s,server ip:%s:%s" % (error,self.host,self.port)
            self.succ=False
       
    def mongo_conn(self):
        try:
            #self.connection=pymongo.MongoClient(host=self.host, port=int(self.port),serverSelectionTimeoutMS=3)
            #uri='mongodb://' + user + ':' + pwd + '@' + server + ':' + port +'/'+ db_name
            uri="mongodb://%s:%s@%s:%s/%s" % (self.user,self.passwd,self.host,self.port,self.dbname)
            #print uri
            self.connection=pymongo.MongoClient(uri)
            #self.connection=pymongo.MongoClient(host=self.host, port=int(self.port),serverSelectionTimeoutMS=3)
            return self.connection
        except Exception as error:
            print 'mongo  connect fail %s' % (error)
    def admin_comm(self,stmt):
        return self.conn.admin.command(stmt)
def current_op(myconn):
    db=myconn.conn['local']
    #res=collection.find()
    current_op=db.current_op(True)
    #print current_op
    print "%-8s %-10s %-10s %-20s %-10s %-10s %-20s %s" % ('opid','desc','op','ns','secs','wLock','client','query')
    for one in current_op['inprog']:
        #print one.get('client','me')
        #print one
        if one.get('op','none')=='none':
            continue
        print "%-8s %-10s %-10s %-20s %-10s %-10s %-20s %s" % (one.get('opid','none'),one['desc'],one.get('op','none'),one.get('ns','none'),one.get('secs_running','none'),one.get('waitingForLock','none'),one.get('client','none'),one.get('query','none')) 

def slow_log(myconn):
    '获取慢日志'
    db=myconn.conn['local']
    collection=db.system.profile
    #log=collection.find({"op":{ "$ne":'command'}).sort({ "ts" : -1 })
    log=collection.find({"$and": [{"op":{ "$ne":'command'}},{"ns":{"$ne":"local.oplog.rs"}}]}).sort([('ts',-1)])
    for one in log:
        #print one['ts']
        #data['updata_time']+datetime.timedelta(hours=8)
        ts=str(one['ts']+datetime.timedelta(hours=8))[0:19]
        print "%-10s %-10s %-8s %-20s %-10s %-20s %-8s %-8s %-8s " %(one['op'],one['ns'],one['millis'],ts,one.get('client','none'),one.get('user','none'),one.get('nscanned','none'),one.get('nscannedObjects','none'),one.get('nreturned','none'))
        #print "  %s" % (one.get('query','none'))
        if one.get("execStats"):
            print "    %s" % (one.get("execStats",'none'))

def count_coll(myconn):
    '返回每个集合的条目'
    try:
        alldb=myconn.conn.database_names()
        for one in alldb:
            if one not in ('admin','local'):
                print "[ {} ]:".format(one)
                db=myconn.conn[one]
                all_coll=db.collection_names()
                for one in all_coll:
                    onecol=db[one]
                    col_count=onecol.find().count()
                    print "%-30s %-30s" % (one,col_count)
                    #print all_coll 
    except Exception, error:    
        print error
    
def user_list(myconn):
    '列出数据库用户列表'
    try:
        db=myconn.conn['admin']
        col=db['system.users']
        userlist=col.find()
        #print userlist
        for one in userlist:
            msg=""
            msg="""[ user_db: {} {} ]""".format(one['user'],one['db'])
            roles=""
            for onerole in one["roles"]:
                roles=roles+"\n    db:%-15s role:%-20s" % (onerole['db'],onerole["role"])
            allmsg=msg+roles+"\n"
            print allmsg
    except Exception, error:
        print error
    
def repl_status(myconn):
    '查找复制集信息'
    try:
        db=myconn.conn['admin']
        replstatus=db.command("replSetGetStatus")
        print "[ {} ]".format(replstatus["set"])
        for one in replstatus["members"]:
            onemsg="""name:{}
stateStr:{}
health:{}
uptime:{}
""".format(one['name'],one["stateStr"],one["health"],one["uptime"])
            print onemsg
    except Exception, error:
        print error

def repl_conf(myconn):
    '查找复制集的配置信息'
    try:
        db=myconn.conn['admin']
        replconf=db.command("replSetGetConfig")
        print "[ {} ]".format(replconf["config"]["_id"])
        for one in replconf["config"]["members"]:
            onemsg="""host:{}
hidden:{}
priority:{}
slaveDelay:{}
votes:{}
""".format(one['host'],one['hidden'],one['priority'],one['slaveDelay'],one['votes'])
            print onemsg
    except Exception, error:
        print error
    
    
def mongo_conn(host,port,user,password,dbname):
    '连接mongo'
    try:
        myconn=mymongo(host,port,user,password,dbname)
        if   myconn.succ:
            return True,myconn
        return False,'连接失败'
    except Exception, error:
        print error
        return False,error


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='mgongo tools')
    parser.add_argument('-p','--port', type=int,required=True,help="指定实例端口")
    parser.add_argument('-i','--ip', type=str,required=True,help="ip")
    parser.add_argument('-u','--user', type=str,required=True,help="用户名")
    parser.add_argument('-a','--password', type=str,required=True,help="验证密码")
    parser.add_argument('-sl','--slowlog', action='store_true',default=False,help='查看慢日志')
    parser.add_argument('-c','--count', action='store_true',default=False,help='统计collction的文档数')
    parser.add_argument('-ul','--userlist', action='store_true',default=False,help='列出系统用户及权限')
    parser.add_argument('-co','--currentop', action='store_true',default=False,help='查看当前连接线程')
    parser.add_argument('-rs','--replstatus', action='store_true',default=False,help='查看rs.status')
    parser.add_argument('-rc','--replconf', action='store_true',default=False,help='查看rs.config')
    args = parser.parse_args()
    port = args.port
    slowlog = args.slowlog
    count=args.count
    userlist=args.userlist
    currentop=args.currentop
    replstatus=args.replstatus
    replconf=args.replconf
    host=args.ip
    user=args.user
    password=args.password
    mongo_status,myconn=mongo_conn(host,port,user,password,'admin')
    if mongo_status:
        if slowlog:
            slow_log(myconn)
        if count:
            count_coll(myconn)
        if userlist:
            user_list(myconn)
        if currentop:
            current_op(myconn)
        if replstatus:
            repl_status(myconn)
        if replconf:
            repl_conf(myconn)

 

posted @ 2018-11-21 17:17  vansky  阅读(380)  评论(0编辑  收藏  举报