#!/bin/bash
# Script name: httpmonitor.sh
# Author: wanghongwei
# Date: 2023-11-30
# Version: 1.0
# Description: A script to monitor http request and send email alerts
# Description: 使用 cURL 请求网页,如果连续三次失败,则发送告警信息
# Usage: ./httpmonitor.sh
# Define lockfile and add exclusive lock
LOCKFILE=/var/run/httpmonitor.lock
exec 200>$LOCKFILE
flock -n 200
if [ $? != 0 ]; then
echo "Fatal: The script is already running!" && exit 1
fi
trap "exec 200>&-; rm -f $LOCKFILE; exit" SIGINT SIGTERM
# Define the logfile
LOGFILE=/var/log/httpmonitor.log
# Define the email subject and recipient
SUBJECT="HTTP Requests Failure"
RECIPIENT="[email protected]"
# Define the fail count and url
FAIL_COUNT=0
URL=https://www.example.com
while true; do
# Request the URL and obtain the HTTP return code
DATE=$(date +"%Y-%m-%d %H:%M:%S")
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
echo -e "${DATE}\t${URL}\t${HTTP_CODE}" >>$LOGFILE
# Count the number of failures
if [ $HTTP_CODE -eq 200 ]; then
FAIL_COUNT=0
else
FAIL_COUNT=$((FAIL_COUNT + 1))
fi
# Determine if the number of failures has reached 3
if [ $FAIL_COUNT -eq 3 ]; then
echo -e "网站 $URL 请求异常,请检查网络连接." | mailx -s "$SUBJECT" "$RECIPIENT"
sleep 30
FAIL_COUNT=0
fi
# Sleep for 2 seconds before checking again
sleep 2
done
标签:COUNT,网页,URL,httpmonitor,监控,正常性,FAIL,HTTP,Define
From: https://www.cnblogs.com/wanghongwei-dev/p/17866793.html