423212 发表于 2017-9-7 13:52:55

zabbix监控数据库

目录:
    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)
            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['keys']
                server_info['key_space_db_expires'] = server_info['expires']
                server_info['key_space_db_avg_ttl'] = server_info['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)

            {
                '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', 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]
查看完整版本: zabbix监控数据库