设为首页 收藏本站
查看: 1141|回复: 0

[经验分享] zabbix监控数据库

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2017-9-7 13:52:55 | 显示全部楼层 |阅读模式
目录:
    zabbix && mongodb......1-1346
    zabbix && redis........1349-3727
    zabbix && mysql........3731-end

//zabbix 监控mongodb

cat /etc/zabbix/zabbix_agentd.d/userparameter_mongo.conf

UserParameter=mongo.service,ps -ef | grep mongo |grep -v grep |wc -l
UserParameter=mongo.mem_resident,echo "db.serverStatus().mem"| mongo|grep resident | cut -d ":" -f 2 |cut -d "," -f 1| cut -d " " -f 2
UserParameter=mongo.mem_virtual,echo "db.serverStatus().mem"| mongo|grep virtual | cut -d ":" -f 2 |cut -d "," -f 1| cut -d " " -f 2
UserParameter=mongo.mem_mapped,echo "db.serverStatus().mem"| mongo|grep '\bmapped\b' | cut -d ":" -f 2 |cut -d "," -f 1| cut -d " " -f 2
UserParameter=mongo.network
  • ,echo "db.serverStatus().network"|mongo | grep $1 | cut -d ":" -f 2 |cut -d "," -f1 |cut -d " " -f 2
    UserParameter=mongo.index
  • ,echo "db.serverStatus().indexCounters"|mongo | grep $1| cut -d ":" -f 2 |cut -d "," -f1 |cut -d " " -f 2
    UserParameter=mongo.connection_current,echo "db.serverStatus().connections"| mongo| grep current|cut -d ":" -f 2|cut -d "," -f 1|cut -d " " -f 2
    UserParameter=mongo.connection_available,echo "db.serverStatus().connections"| mongo| grep current| cut -d ":" -f 3|cut -d "," -f 1 |cut -d " " -f 2
    UserParameter=mongo.opcounters
  • ,echo "db.serverStatus().opcounters" |mongo | grep $1|cut -d ":" -f 2|cut -d "," -f 1 |cut -d " " -f 2
    UserParameter=mongo.rpstatus,echo "rs.status()"| mongo | grep myState| cut -d ":" -f 2| cut -d "," -f 1 |cut -d " " -f 2
    UserParameter=mongo.queue_write,echo "db.serverStatus().globalLock.currentQueue.writers"|mongo |sed -n 3p
    UserParameter=mongo.queue_reader,echo "db.serverStatus().globalLock.currentQueue.readers"|mongo |sed -n 3p
    UserParameter=mongo.backgroundFlush,echo "db.serverStatus().backgroundFlushing.last_ms" |mongo |sed -n 3p
    UserParameter=mongo.curosor_Totalopen,echo "db.serverStatus().cursors.totalOpen" |mongo |sed -n 3p
    UserParameter=mongo.curospr_timedOu,echo "db.serverStatus().cursors.timedOut" |mongo |sed -n 3p
    UserParameter=mongo.pagefaults,echo "db.serverStatus().extra_info.page_faults" |mongo|sed -n 3p
    UserParameter=mongo.oplog_storetime,echo "db.printReplicationInfo()"|mongo|sed -n 4p|cut -d "(" -f 2|cut -d "h" -f 1

    //根据xml文件直接导入模板++下载模板

    http://pan.baidu.com/s/1hsMkxiW



    +++++++++++++++++++++++++监控redis+++++++++++
    //配置文件
    cat userparameter_redis.conf
    # Redis
    # This content is licensed GNU GPL v2
    # Author: Alexey Dubkov <alexey.dubkov@gmail.com>

    # Discovery
    UserParameter=redis.discovery,/etc/zabbix/script/redis/zbx_redis_stats.py -p 6379 -a Cloudcc@2017 192.168.5.205 list_key_space_db

    # Return Redis statistics
    UserParameter=redis
  • ,/etc/zabbix/script/redis/zbx_redis_stats.py -p 6379 -a Cloudcc@2017 $1 $2 $3

    vim /etc/hosts
    //添加
    172.16.1.172    L-172.16.1.172

    //安装python依赖包
    yum -y install python-pip
    pip install argparse
    pip install redis

    mkdir -p /etc/zabbix/script/redis
    chmod +x /etc/zabbix/script/redis/zbx_redis_stats.py


    =================python程序============================
    cat /etc/zabbix/script/redis/zbx_redis_stats.py

    #!/usr/bin/python

    import sys, redis, json, re, struct, time, socket, argparse

    parser = argparse.ArgumentParser(description='Zabbix Redis status script')
    parser.add_argument('redis_hostname',nargs='?')
    parser.add_argument('metric',nargs='?')
    parser.add_argument('db',default='none',nargs='?')
    parser.add_argument('-p','--port',dest='redis_port',action='store',help='Redis server port',default=6379,type=int)
    parser.add_argument('-a','--auth',dest='redis_pass',action='store',help='Redis server pass',default=None)
    args = parser.parse_args()

    zabbix_host = '192.168.5.209'       # Zabbix Server IP
    zabbix_port = 10051             # Zabbix Server Port

    # Name of monitored server like it shows in zabbix web ui display
    redis_hostname = args.redis_hostname if args.redis_hostname else socket.gethostname()

    class Metric(object):
        def __init__(self, host, key, value, clock=None):
            self.host = host
            self.key = key
            self.value = value
            self.clock = clock

        def __repr__(self):
            result = None
            if self.clock is None:
                result = 'Metric(%r, %r, %r)' % (self.host, self.key, self.value)
            else:
                result = 'Metric(%r, %r, %r, %r)' % (self.host, self.key, self.value, self.clock)
            return result

    def send_to_zabbix(metrics, zabbix_host='127.0.0.1', zabbix_port=10051):
        result = None
        j = json.dumps
        metrics_data = []
        for m in metrics:
            clock = m.clock or ('%d' % time.time())
            metrics_data.append(('{"host":%s,"key":%s,"value":%s,"clock":%s}') % (j(m.host), j(m.key), j(m.value), j(clock)))
        json_data = ('{"request":"sender data","data":[%s]}') % (','.join(metrics_data))
        data_len = struct.pack('<Q', len(json_data))
        packet = 'ZBXD\x01'+ data_len + json_data

        # For debug:
        # print(packet)
        # print(':'.join(x.encode('hex') for x in packet))

        try:
            zabbix = socket.socket()
            zabbix.connect((zabbix_host, zabbix_port))
            zabbix.sendall(packet)
            resp_hdr = _recv_all(zabbix, 13)
            if not resp_hdr.startswith('ZBXD\x01') or len(resp_hdr) != 13:
                print('Wrong zabbix response')
                result = False
            else:
                resp_body_len = struct.unpack('<Q', resp_hdr[5:])[0]
                resp_body = zabbix.recv(resp_body_len)
                zabbix.close()

                resp = json.loads(resp_body)
                # For debug
                # print(resp)
                if resp.get('response') == 'success':
                    result = True
                else:
                    print('Got error from Zabbix: %s' % resp)
                    result = False
        except:
            print('Error while sending data to Zabbix')
            result = False
        finally:
            return result

    def _recv_all(sock, count):
        buf = ''
        while len(buf)<count:
            chunk = sock.recv(count-len(buf))
            if not chunk:
                return buf
            buf += chunk
        return buf

    def main():
        if redis_hostname and args.metric:
            client = redis.StrictRedis(host=redis_hostname, port=args.redis_port, password=args.redis_pass)
            server_info = client.info()

            if args.metric:
                if args.db and args.db in server_info.keys():
                    server_info['key_space_db_keys'] = server_info[args.db]['keys']
                    server_info['key_space_db_expires'] = server_info[args.db]['expires']
                    server_info['key_space_db_avg_ttl'] = server_info[args.db]['avg_ttl']

                def llen():
                    print(client.llen(args.db))

                def llensum():
                    llensum = 0
                    for key in client.scan_iter('*'):
                        if client.type(key) == 'list':
                            llensum += client.llen(key)
                    print(llensum)

                def list_key_space_db():
                    if args.db in server_info:
                        print(args.db)
                    else:
                        print('database_detect')

                def default():
                    if args.metric in server_info.keys():
                        print(server_info[args.metric])

                {
                    'llen': llen,
                    'llenall': llensum,
                    'list_key_space_db': list_key_space_db,
                }.get(args.metric, default)()

            else:
                print('Not selected metric')
        else:
            client = redis.StrictRedis(host=redis_hostname, port=args.redis_port, password=args.redis_pass)
            server_info = client.info()

            a = []
            for i in server_info:
                a.append(Metric(redis_hostname, ('redis[%s]' % i), server_info))

            llensum = 0
            for key in client.scan_iter('*'):
                if client.type(key) == 'list':
                    llensum += client.llen(key)
            a.append(Metric(redis_hostname, 'redis[llenall]', llensum))

            # Send packet to zabbix
            send_to_zabbix(a, zabbix_host, zabbix_port)

    if __name__ == '__main__':
        main()

    =================python程序结束============================

    //更改位置
    zabbix_host = '172.16.1.186'         # Zabbix Server IP
    zabbix_port = 10051                # Zabbix Server Port


    //测试zbx_redis_status.py是否正常,查看redis版本:
    /etc/zabbix/script/redis/zbx_redis_stats.py -p 6379 -a MyPassword L-172.16.1.172 gcc_version none

    //导入redis模板++下载地址
    http://pan.baidu.com/s/1hscjn3Q


    ++++++++++++++监控mysql+++++++++++++

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    //清空默认配置
    echo > userparameter_mysql.conf

    vim /etc/zabbix/zabbix_agentd.conf

    UserParameter=mysql.version,mysql -V
    UserParameter=mysql.status
  • ,/usr/local/zabbix/chk_mysql.sh $1
    UserParameter=mysql.ping,netstat -ntpl |grep 3317 |grep mysql |wc |awk '{print $1}'

    vim /usr/local/zabbix/chk_mysql.sh
    mkdir 777 /usr/local/zabbix/chk_mysql.sh
    ================shell脚本====================

    #!/bin/sh
    # -------------------------------------------------------------------------------
    # FileName:    check_mysql.sh
    # Revision:    1.0
    # Date:        2016/04/22
    # Author:      tim
    # Email:       mchdba@sohu.com
    MYSQL_SOCK="/usr/local/mysql/mysql.sock"
    MYSQL_USER='zabbix'
    MYSQL_PWD='ys_ipowerlong0418'
    MYSQL_HOST='127.0.0.1'
    MYSQL_PORT='3306'
    ARGS=1
    if [ $# -ne "$ARGS" ];then
        echo "Please input one arguement:"
    fi
    case $1 in
        Uptime)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK status|cut -f2 -d":"|cut -f1 -d"T"`
                echo $result
                ;;
            Com_update)
                result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_update"|cut -d"|" -f3`
                echo $result
                ;;
            Slow_queries)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK status |cut -f5 -d":"|cut -f1 -d"O"`
                    echo $result
                    ;;
        Com_select)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_select"|cut -d"|" -f3`
                    echo $result
                    ;;
        Com_rollback)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_rollback"|cut -d"|" -f3`
                    echo $result
                    ;;
        Questions)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK status|cut -f4 -d":"|cut -f1 -d"S"`
                    echo $result
                    ;;
        Com_insert)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_insert"|cut -d"|" -f3`
                    echo $result
                    ;;
        Com_delete)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_delete"|cut -d"|" -f3`
                    echo $result
                    ;;
        Com_commit)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_commit"|cut -d"|" -f3`
                    echo $result
                    ;;
        Bytes_sent)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Bytes_sent" |cut -d"|" -f3`
                    echo $result
                    ;;
        Bytes_received)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Bytes_received" |cut -d"|" -f3`
                    echo $result
                    ;;
        Com_begin)
            result=`/usr/local/mysql/bin/mysqladmin -u$MYSQL_USER -h$MYSQL_HOST -p${MYSQL_PWD} -S $MYSQL_SOCK extended-status |grep -w "Com_begin"|cut -d"|" -f3`
                    echo $result
                    ;;
                            
            *)
            echo "Usage:$0(Uptime|Com_update|Slow_queries|Com_select|Com_rollback|Questions)"
            ;;
    esac

    =============shell脚本结束========================

    在zabix web管理界面直接引用mysql模板就可以



  • 运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
    2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
    3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
    4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
    5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
    6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
    7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
    8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

    所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-404158-1-1.html 上篇帖子: 为什么有的扣了金币,不能分享啊 下篇帖子: zabbix安装配置
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    扫码加入运维网微信交流群X

    扫码加入运维网微信交流群

    扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

    扫描微信二维码查看详情

    客服E-mail:kefu@iyunv.com 客服QQ:1061981298


    QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


    提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


    本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



    合作伙伴: 青云cloud

    快速回复 返回顶部 返回列表