python通过pycurl模块,提交json数据,监控web站点,并通过nagios报警。
执行脚本python check_pinggu.py ip port host status_code
其中:
ip和port组成proxy
host为domain
status_code为状态码
脚本功能:以json格式post数据到指定的url,并判断状态码
和curl对比:
curl -x ip:port -H “Content-Type:application/json;charset=utf-8” -X POST -d ‘{“city”:”bj”,”district”:”cy”,”bldgarea”:80,”floor”:”8”,”height”:”28”}’ http://domain
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#监控
#exit(0),返回0,表示ok,没有异常
#exit(1),返回1,表示warning,会触发warning报警
#exit(2),返回2,表示critical,会触发critical报警
import sys
import pycurl
import StringIO
#参数不够直接退出程序
if len(sys.argv) != 5:
print "Usage : python check_pinggu.py ip port host status_code"
exit(1)
ip=sys.argv[1]
port=sys.argv[2]
host=sys.argv[3]
status_code=sys.argv[4]
proxy=ip+':'+port
head = ['Content-Type:application/json;charset=utf-8']
s = '{"city":"bj","district":"cy","bldgarea":80,"floor":"8","height":"28"}'
checkurl = "http://"+host+"/v1/assess"
#print checkurl
curl=pycurl.Curl()
b=StringIO.StringIO()
#写回调
curl.setopt(curl.WRITEFUNCTION, b.write)
curl.setopt(pycurl.FOLLOWLOCATION, 1)
#重定向次数
curl.setopt(pycurl.MAXREDIRS, 2)
curl.setopt(pycurl.URL, checkurl)
curl.setopt(pycurl.HTTPHEADER, head)
curl.setopt(pycurl.CUSTOMREQUEST, "POST")
curl.setopt(pycurl.POSTFIELDS, s)
#设置代理
curl.setopt(pycurl.PROXY, proxy)
#超时
curl.setopt(pycurl.CONNECTTIMEOUT, 60)
curl.setopt(pycurl.TIMEOUT, 300)
curl.perform()
#print b.getvalue()
#b.close()
status=curl.getinfo(curl.HTTP_CODE)
#print status
curl.close()
if status != int(status_code):
print 'HTTP ERROR: Status line output is '+ status + ' - interface is something wrong'
exit(2)
else:
print 'HTTP OK: Status line output matched '+ status_code +' - interface is ok'
由于是通过nagios进行报警,因此需在脚本中设置返回值,不同的返回值会触发不同的状态报警。
exit(0),返回0,表示ok,没有异常
exit(1),返回1,表示warning,会触发warning报警
exit(2),返回2,表示critical,会触发critical报警