zabbix监控LVS连接的状态

一、编写lvs监控脚本

vim /etc/zabbix/zabbix_agentd.script/lvs_status.sh

#!/bin/bash
function lvs_total {
#获取lvs的总处理请求数
sudo /sbin/ipvsadm -Ln | awk ‘{print $6}’ |awk ‘BEGIN{sum=0}{sum+=$1}END{print sum}’
}

function lvs_real1 {
#获取realserver10.129.13.208的处理请求数
sudo /sbin/ipvsadm -Ln | grep ‘10.129.13.208’ |awk ‘{print $6}’
}

function lvs_real2 {
#获取realserver10.129.13.208的处理请求数
sudo /sbin/ipvsadm -Ln | grep ‘10.129.13.208’ |awk ‘{print $6}’
}
$1

 

二、创建/etc/zabbix/zabbix_agentd.d/userparameter_lvs.conf

UserParameter=lvs[*],/etc/zabbix/zabbix_agentd.script/lvs_status.sh $1

三、修改sudo的配置文件

#visudo

添加如下内容

zabbix   ALL=(ALL)  NOPASSWD:/sbin/ipvsadm

把Defaults  requiretty 这行注释掉,如果不注释掉这行会出现以下问题:

sudo: sorry, you must have a tty to run sudo
导致这问题的原因是 sudo默认需要在 tty终端里才能正确被调用,我们可以通过修改 /etc/sudoers配置文件来解决这个问题

四、重启zabbix_agent客户端

/etc/init.d/zabbix-agent restart

五、图形化界面配置(略)

Python利用Zabbix API定时报告存在报警的机器(更新:针对zabbix3.x)

前一篇Python利用Zabbix API定时报告存在报警的机器做完后发现仅能运行在zabbix2.x环境,由于我们有一部分环境是在zabbix3.x下检测的,故需要能够运行在3.x下。可是跑脚本发现如下问题:

zabbix2.x返回trigger.get:

{u'jsonrpc': u'2.0', u'result': [{u'hostid': u'10271', u'description': u'Too many MongoDB page_faults', u'hostname': u'192.168.1.161', u'host': u'192.168.1.161', u'priority': u'4', u'triggerid': u'19429'}, {u'hostid': u'10263', u'description': u'Tcp Port 18083 Status', u'hostname': u'192.168.1.153', u'host': u'192.168.1.153', u'priority': u'4', u'triggerid': u'18542'}, {u'hostid': u'10255', u'description': u'Zabbix agent on {HOST.NAME} is unreachable for 5 minutes', u'hostname': u'10.25.20.103', u'host': u'10.25.20.103', u'priority': u'3', u'triggerid': u'17938'}, {u'hostid': u'10281', u'description': u'Free disk space is less than 20% on volume /', u'hostname': u'192.168.1.143', u'host': u'192.168.1.143', u'priority': u'2', u'triggerid': u'18662'}, {u'hostid': u'10231', u'description': u'Free disk space is less than 20% on volume /file', u'hostname': u'192.168.2。108', u'host': u'.192..168.2.108', u'priority': u'2', u'triggerid': u'17499'}, {u'hostid': u'10271', u'description': u'Free disk space is less than 20% on volume /', u'hostname': u'192.168.1.161', u'host': u'192.168.1.161', u'priority': u'2', u'triggerid': u'18421'}, {u'hostid': u'10196', u'description': u'Free disk space is less than 20% on volume /data', u'hostname': u'192.168.1.113', u'host': u'192.168.1.113', u'priority': u'2', u'triggerid': u'16368'}, {u'hostid': u'10257', u'description': u'Free disk space is less than 20% on volume /app', u'hostname': u'192.168.20.105', u'host': u'192.168.20.105', u'priority': u'2', u'triggerid': u'19440'}, {u'hostid': u'10279', u'description': u'Free disk space is less than 20% on volume /', u'hostname': u'192.168.1.149', u'host': u'192.168.1.149', u'priority': u'2', u'triggerid': u'18605'}, {u'hostid': u'10231', u'description': u'Lack of free swap space on {HOST.NAME}', u'hostname': u'192.168.2.108', u'host': u'192.168.2.108', u'priority': u'2', u'triggerid': u'17489'}, {u'hostid': u'10197', u'description': u'Free disk space is less than 20% on volume /data', u'hostname': u'192.168.1.114', u'host': u'192.168.1.114', u'priority': u'2', u'triggerid': u'16374'}, {u'hostid': u'10232', u'description': u'OSS Dev Status Not OK', u'hostname': u'ESB unit test server', u'host': u'192.168.1.200', u'priority': u'1', u'triggerid': u'18749'}, {u'hostid': u'10234', u'description': u'SpKeyAvailableDaysTrigger', u'hostname': u'zabbix_server', u'host': u'zabbix_server', u'priority': u'1', u'triggerid': u'18717'}], u'id': 1}

zabbix3.x返回trigger.get:

{u'jsonrpc': u'2.0', u'result': [{u'status': u'0', u'functions': [{u'itemid': u'30286', u'function': u'last', u'triggerid': u'16195', u'parameter': u'', u'functionid': u'16164'}], u'description': u'Mysql Replication error on {HOST.NAME}', u'state': u'0', u'url': u'', u'type': u'0', u'templateid': u'16191', u'lastchange': u'1478593366', u'value': u'1', u'priority': u'3', u'triggerid': u'16195', u'flags': u'0', u'comments': u'', u'error': u'', u'expression': u'{16164}<>2'}, {u'status': u'1', u'functions': [{u'itemid': u'23310', u'function': u'last', u'triggerid': u'13500', u'parameter': u'0', u'functionid': u'12909'}], u'description': u'Lack of free swap space on {HOST.NAME}', u'state': u'0', u'url': u'', u'type': u'0', u'templateid': u'10012', u'lastchange': u'1464343050', u'value': u'1', u'priority': u'2', u'triggerid': u'13500', u'flags': u'0', u'comments': u'It probably means that the systems requires more physical memory.', u'error': u'', u'expression': u'{12909}<50'}, {u'status': u'0', u'functions': [{u'itemid': u'30068', u'function': u'last', u'triggerid': u'16102', u'parameter': u'0', u'functionid': u'15705'}], u'description': u'Free disk space is less than 20% on volume /app', u'state': u'0', u'url': u'', u'type': u'0', u'templateid': u'0', u'lastchange': u'1487316369', u'value': u'1', u'priority': u'2', u'triggerid': u'16102', u'flags': u'4', u'comments': u'', u'error': u'', u'expression': u'{15705}<20'}], u'id': 1}

仔细对比能发现,3.0中没有任何关于host、hostname或者hostid的信息,这里让我痛苦了好久,网上也没有现成的办法,最后还是看zabbix的官方api想到了办法——根据triggerids来查询相关host信息。

脚本如下:

#!/usr/bin/python
#coding:utf-8
import json
import urllib2
from urllib2 import URLError
import sys
import zabbix_sendmail
#接收人
mailtolist = ['test@163.com',]
#格式:zabbix地址,zabbix帐号,zabbix密码,邮件标题
zabbix_addresses=['http://test1.zabbix.com,admin,123456,test1','http://test2.zabbix.com,admin,123456,test2','http://test3.zabbix.com,admin,123456,test3']
class ZabbixTools:
    def __init__(self,address,username,password):
                                                                       
        self.address = address
        self.username = username
        self.password = password
                                                                       
        self.url = '%s/api_jsonrpc.php' % self.address
        self.header = {"Content-Type":"application/json"}
                                                                       
                                                                       
                                                                       
    def user_login(self):
        data = json.dumps({
                           "jsonrpc": "2.0",
                           "method": "user.login",
                           "params": {
                                      "user": self.username,
                                      "password": self.password
                                      },
                           "id": 0
                           })
                                                                       
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
                                                                   
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Auth Failed, please Check your name and password:", e.code
        else:
            response = json.loads(result.read())
            result.close()
            #print response['result']
            self.authID = response['result']
            return self.authID
                                                                           
    def trigger_get(self):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method":"trigger.get",
                           "params": {
                                      "output": [
                                                "triggerid",
                                                "description",
                                                "priority"
                                                ],
                                      "filter": {
                                                 "value": 1
                                                 },
                                      "expandData":"hostname",
                                      "sortfield": "priority",
                                      "sortorder": "DESC"
                                    },
                           "auth": self.user_login(),
                           "id":1              
        })
                                                                       
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])
                                                                       
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Error as ", e
        else:
            response = json.loads(result.read())
            result.close()
            issues = response['result']
            content = ''
            if issues:
                for line in issues:
                    triggerid=line['triggerid']
                    host=self.host_get(triggerid)
                    content = content + "%s:%s\r\n" % (host,line['description'])
            return content
   
   def host_get(self,triggerid):
        data = json.dumps({
                           "jsonrpc":"2.0",
                           "method":"host.get",
                           "params": {
                                     "triggerids": triggerid
                                    },
                           "auth": self.user_login(),
                           "id":1
        })

        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Error as ", e
        else:
            response = json.loads(result.read())
            result.close()
            issues = response['result']
            host=issues[0]['host']
            return host

                                                                           
if __name__ == "__main__":
    for zabbix_addres in zabbix_addresses:
        address,username,password,subject = zabbix_addres.split(',')
        z = ZabbixTools(address=address, username=username, password=password)
        content = z.trigger_get()
        zabbix_sendmail.send_mail(mailtolist, subject, content)
    print "Done!"