* * * * * cd /data/openfalcon/agent/userdefine && ./http.check 1>>/tmp/1.txt 2>&1
#!/usr/bin/env python
#coding: utf-8

import os, sys, re
import json
import requests
import time
import urllib2, base64
from socket import *

def checkHttp(httpurl,neirong=''):
    # 获取数据
    try:
        r = requests.get(httpurl, timeout=3)
        # 判断http返回码是不是正常
        if r.status_code in [ 200, 201, 301, 302]:
            pass
        else:
            return 111
        # 判断返回的里面有没有指定字符串
        results = re.findall('%s'%neirong,r.text)
        if len(results) > 0:
            return 0
        else:
            return 111
    except Exception:
        return 111

# 上报
def uploadToAgent(p):
    method = "POST"
    handler = urllib2.HTTPHandler()
    opener = urllib2.build_opener(handler)
    url = "http://127.0.0.1:1988/v1/push"
    request = urllib2.Request(url, data=json.dumps(p))
    request.add_header('Content-Type','application/json')
    request.get_method = lambda: method
    try:
        connection = opener.open(request)
    except urllib2.HTTPError,e:
        connection = e

    if connection.code == 200:
        print connection.read()
    else:
        print '{"err":1,"msg":"%s"}' % connection


print "开始 "

# 准备上报数据
def zuzhuangData(tags = '', value = ''):
    endpoint = "192.168.0.88"
    metric = "userdefine"
    key = "remotehttpcheck"
    timestamp = int(time.time())
    step = 60
    vtype = "GAUGE"

    i = {
            'Metric' :'%s.%s'%(metric,key),
            'Endpoint': endpoint,
            'Timestamp': timestamp,
            'Step': step,
            'value': value,
            'CounterType': vtype,
            'TAGS': tags
            }
    return i

p = []
with open("./http.txt") as f:
    for line in f:
        results = re.findall("(\S+)",line)
        print results
        httpurl = results[0]
        description = results[1]
        neirong = results[2]
    tags = "project=ops,"
        tags += "httpurl=%s,description=%s,neirong=%s"%(httpurl,description,neirong)
        value = checkHttp(httpurl,neirong)
        p.append(zuzhuangData(tags,value))

print json.dumps(p, sort_keys=True,indent = 4)

uploadToAgent(p)

报警

each(metric=userdefine.remotehttpcheck project=ops)
all(#3) != 0
Copyright © opschina.org 2017 with zzlyzq@gmail.com all right reserved,powered by Gitbook该文件修订时间: 2017-07-11 11:32:48

results matching ""

    No results matching ""