nagios自带的http-check插件主要是检测地址url是否可以访问,在web+中间件的架构中容易出现url能访问,但是后台中间件拓机的情况,因为最近在自学python,所以写了个脚本检测url title的脚本,若中间件挂掉之后,则当前url的titile一定会发生变化,也可以专门设置一个test.jsp的页面用于检测中间件、数据源的健康状态。
第一步:写python脚本
首先要知道的是:
Nagios 每次在查询一个服务的状态时,产生一个子进程,并且它使用来自该命令的输出和退出代码来确定具体的状态。退出状态代码的含义如下所示:
- OK —退出代码 0—表示服务正常地工作。
- WARNING —退出代码 1—表示服务处于警告状态。
- CRITICAL —退出代码 2—表示服务处于危险状态。
- UNKNOWN —退出代码 3—表示服务处于未知状态
#!/usr/bin/python
#coding:utf-8
__author__ = 'dwj'
import getopt,sys,urllib,re
class monitor:
def __init__(self):
pass
#print '这是一个监控脚本,输入url和你希望得到的标题页面,如果是你设定的页面就返回OK,否则返回你想要的内容,也可以发告警邮件'
def sgethtml(self,url):
self.url=url
page=urllib.urlopen(url)
html=page.read()
return html
def monitor(self,title,html):
self.title=title
self.html=html
find_title=r'<TITLE>(.*)</TITLE>'
find_titled=re.compile(find_title,re.I)
t=re.findall(find_titled,html) #找到的是一个列表
t=t[0].strip() #去除前后空格
if t==title:
print 'The title is find! ok'
sys.exit(0)
else:
print t.decode('utf-8')
print 'The title is not find!! pls check it!'
sys.exit(3)
def useage():
print('This is a test fun')
#print 'hhh'
m=monitor()
try:
options,args=getopt.getopt(sys.argv[1:],'u:t:',['url=','title='])
except getopt.GetoptError:
sys.exit(2)
#print options,args
for name,value in options:
if name in ('-u','--url'):
url=value
if name in ('-t','--title'):
title=value
html=m.sgethtml(url)
m.monitor(title,html)
第二步:将python脚本注册为nagios命令
打开nagios的command.cfg的配置文件
添加如下信息:
define command{
command_name dwj_check
command_line python /usr/lib/nagios/plugins/http_check.py -u $ARG1$ -t $ARG2$
}
第三步:编写service.cfg
define service {
use generic-service
host_name testhost
service_description www_http
check_command dwj_check!http://192.168.18.12!Naigos #nagios的参数使用!来分隔 若title中含有空格则使用双引号将其括起来!
}重启之后,在nagios就可以看到新添加的服务监控:
至此OK了
本文介绍如何使用Python脚本来自定义Nagios监控服务,通过检查URL标题判断中间件状态,实现更精确的监控需求。
1148

被折叠的 条评论
为什么被折叠?



