Web 状态码检测监控提醒

| 选择喜欢的代码风格  

Web 检测 Shell 脚本:


提醒可以通过钉钉,或者邮件,或者短信接口等方式:

#!/bin/bash

URL=https://commandnotfound.cn/
DING_URL=https://oapi.dingtalk.com/robot/send?access_token={可以申请钉钉开发者获取对应Token}

function SendMsgToDingding(){ 
    curl "${DING_URL}" -H 'Content-Type: application/json' -d "
    {
        \"actionCard\": {
            \"title\": \"o(╥﹏╥)o故障啦\", 
            \"text\": \"Web地址: $URL\n\n状态码: $1\n\n响应时间:${REQUEST_TIME}秒\n\n当前时间:${DT}\n\n\",
            \"hideAvatar\": \"0\", 
            \"btnOrientation\": \"0\", 
            \"btns\": [
            {
                \"title\": \"URL地址链接\", 
                \"actionURL\": \"$URL\"
            }
        ]
        }, 
        \"msgtype\": \"actionCard\"
    }"
} 

function getHttpRequest()
{
    DT=$(date)
    CODE=$(echo `curl -o /dev/null -s -m 10 --connect-timeout 10 -w %{http_code} "$URL"`)
    REQUEST_TIME=$(curl -o /dev/null -s -w "time_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{time_total}\n" "$URL" | awk /time_total/ | awk -F ': ' '{print $2}')
    if [[ "$REQUEST_TIME" > "2" ]] || [[ "$CODE" -ne 200 ]];then
         SendMsgToDingding $CODE
    else
         :
    fi
}

getHttpRequest
step=5
while true
do
    getHttpRequest
    sleep $step
done

Web 检测 Python 脚本:


本示例采用 Python 3

#!/bin/env python3

import requests
import json
import os
import sys
import subprocess
import time

url = "https://commandnotfound.cn"
api_url = "https://oapi.dingtalk.com/robot/send?access_token={#钉钉 TOKEN#}"
headers = {'Content-Type': 'application/json;charset=utf-8'}
cur_time = time.asctime(time.localtime(time.time()))
CMD_code = '''echo `curl -o /dev/null -s -m 10 --connect-timeout 10 -w %{http_code} "https://www.cjzshilong.cn"`'''
code = subprocess.getoutput(CMD_code)
#print(code)
CMD_time = ''' curl -o /dev/null -s -w "time_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{time_total}\n" "https://www.cjzshilong.cn" | awk /time_total/ | awk -F ': ' '{print $2}' '''
res_time = subprocess.getoutput(CMD_time)
#print(res_time)

def msg(text):
    json_text= {
        "actionCard": {
            "title": "solo状态码报警",
            "text":
             text,
            "hideAvatar": "0",
            "btnOrientation": "0",
            "btns": [
                {
                    "title": "URL链接测试",
                    "actionURL": "https://commandnotfound.cn"
                },
            ]
        },
        "msgtype": "actionCard"
    }
    Text = requests.post(api_url,data=json.dumps(json_text),headers=headers).json()
    return Text

def message():
    mess = "solo网站状态码测试 \n\n Web网址: %s \n\n 状态码:%s \n\n 网站响应时间: %s s \n\n 当前时间:%s \n\n"%(url,code,res_time,cur_time)
    return mess

if __name__ == '__main__':
    if code != '200' or res_time > '2':
      text = message()
      msg(text)
    else:
      pass

Web 检测扩展阅读:


钉钉消息到自定义机器人开发文档参考:获取自定义机器人 Webhook

文章来源:




发表评论