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!"

Python利用Zabbix API定时报告存在报警的机器

由于手上的zabbix服务器有几个,有时会没注意报警短信,又懒得登陆上去看看zabbix,所以用Python利用zabbix的API获取有问题的机器每天早上发到我邮箱,foxmail又是我天天都用的东西,这样我就可以方便地看到所有有问题的机器了

zabbix_sendmail.py

#!/usr/bin/python
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
import sys
#mail_to_list = ['lihuipeng@xxx.com',]
mail_host = 'smtp.163.com'
mail_user = 'testest'     #发件人邮箱帐号
mail_pass = '123456'      #发件人邮箱密码
mail_postfix = '163.com'
def send_mail(to_list,subject,content):
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = ";".join(to_list)
    #msg['to'] = to_list
                                                                                             
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me,to_list,msg.as_string())
        s.close()
        return True
    except Exception,e:
        print str(e)
        return False
                                                                                             
if __name__ == "__main__":
    print sys.argv[1]
    print sys.argv[2]
    print sys.argv[3]
    send_mail(sys.argv[1], sys.argv[2], sys.argv[3])

这个是我用来发邮件的脚本,原理就是连接到163邮箱发送邮件,这里我是注册了一个帐号专门用来发邮件的。

zabbix_report.py

#!/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:
                    content = content + "%s:%s\r\n" % (line['host'],line['description'])
            return content
                                                                           
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!"

这里就是利用API查询信息,然后通过上面的发邮件脚本把信息发出来,效果是这样的:

145315337.png

再添加一个crontab就OK~

本文出自 “运维笔记” 博客,请务必保留此出处http://lihuipeng.blog.51cto.com/3064864/1306261

ps:

可能有的人smtp发送会失败,说是认证没有通过,可以试试修改如下:

#!/opt/venv/bin/python
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
import sys
mail_host = 'smtp.xxxxx.com'
mp = 'password'
mail_postfix = 'xxxxx.com'


def send_mail(to_list,subject,content):
 me = 'xxxxx@xxxxx.com'
 msg = MIMEText(content)
 msg['Subject'] = subject
 msg['From'] = me
 msg['to'] = ";".join(to_list)

 try:
 s = smtplib.SMTP(mail_host,25)
 s.ehlo()
 s.starttls()
 s.ehlo
 s.login(me,mp)
 s.sendmail(me,to_list,msg.as_string())
 s.close()
 return True
 except Exception,e:
 print str(e)
 return False