pycurl+json监控web

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报警

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值