概述
网上有很多使用zabbix监控haproxy的脚本,但大多数都使用的socket方式,而haproxy的stats页面页面我们经常需要访问的,所以我们这次使用python来抓取haproxy的stats页面。
haproxy的stats页面分析
<tr class="active0"><td class=ac><a name="app_push/push496">
当backend正常时,会显示绿色.
<tr class="active4"><td class=ac><a name="app_push/push096">
中间会有黄色的情况,backend反复故障恢复时会产生。 Python脚本抓取
#!/usr/bin/env python #coding=utf-8 #Debug in Python2.7 import urllib2 import sys import re url = sys.argv[1] #url = 'http://10.100.18.78:8888/status' try: response = urllib2.urlopen(url,timeout=5).read(); except: print 'error to connect haproxy.' sys.exit(0) pattern = re.compile('<tr class="active0"><td class=ac><a name="(.*?)"></a>') items = re.findall(pattern, response) data = [] for item in items: #print item data.append(item) if len(data): print data else: print 'ok'
当haproxy有backend故障时,会打印故障服务器,没有故障时显示OK,服务器无法连接,显示’error to connect haproxy.’ 故障显示如下
['app_push/push496', 'app_push/push092']
Zabbix中添加监控项 需要zabbix客户端自定义一个key来关联检查脚本。然后zabbix服务器端设置模板。这里我是用的字符串匹配。
#!/usr/bin/env python from dingding import message import requests import sys import re import time while True: time.sleep(30) url = 'http://10.28.xx.xx:65010/haproxy' try: response = requests.get(url=url, timeout=5).text except: print('error to connect haproxy.') sys.exit(0) pattern = re.compile('<tr class="active0"><td class=ac><a name="(.*?)"></a>') items = re.findall(pattern, response) data = [] for item in items: #print item data.append(item) if len(data): print(data) message(text=data) else: print('ok')
dingding.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' @Author: 风哥 @Email: gujiwork@outlook.com @Create Time: 2019/9/4 ''' import json import requests def message(text): # 告警通知 headers = { 'Content-Type': 'application/json;charset=utf-8', } alarm_user = 'phone1,phone2' notice_url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' at_user = (alarm_user).split(',') json_text = { "msgtype": "text", "at": { "atMobiles": at_user, "isAtAll": False # 为True表示@所有人 }, "text": { "content": (text) } } try: notice = requests.post(notice_url, json.dumps(json_text), headers=headers).content print(json.loads(notice)) except BaseException as e: at_user = [] print(e)