网页正常性监控脚本
网页正常性监控脚本
#!/bin/bash
# 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="wanghongwei-dev@qq.com"
# 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 -I -m 20 -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 60
FAIL_COUNT=0
fi
# Sleep for 2 seconds before checking again
sleep 2
done
持续检测网页正常访问计数
successcount=0; for i in {1..1000}; do curl -I -m 10 -o /dev/null -s -w "request_number: $i\thttp_code: %{http_code}\tsuccesscount: $successcount\n" https://www.example.com && sleep 0.1; done | while read line; do if [[ $line == *"http_code: 200"* ]]; then ((successcount++)); fi; echo $line | sed "s/successcount: [0-9]*/successcount: $successcount/"; done
探测主机端口连通性
#!/bin/bash
export PATH=$PATH:/usr/local/bin
HOST=172.16.0.1
PORT=443
TOTAL_COUNT=0
FAIL_COUNT=0
LOCKFILE=/var/run/tcping-$HOST.lock
LOGFILE=/tmp/tcping-$HOST.log
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
while true; do
DATE=$(date +"%Y-%m-%d %H:%M:%S")
PROBERESULT=$(tcping $HOST $PORT)
if [ $? -eq 1 ]; then
FAIL_COUNT=$((FAIL_COUNT + 1))
fi
TOTAL_COUNT=$((TOTAL_COUNT + 1))
echo -e "$DATE\tProbe result: $PROBERESULT" >>$LOGFILE
echo -e "Total count: $TOTAL_COUNT\tFailure count: $FAIL_COUNT" >>$LOGFILE
sleep 1
done
作者:wanghongwei
版权声明:本作品遵循<CC BY-NC-ND 4.0>版权协议,商业转载请联系作者获得授权,非商业转载请附上原文出处链接及本声明。