Skip to content

Instantly share code, notes, and snippets.

@ChieftainY2k
Last active September 18, 2023 09:34
Show Gist options
  • Save ChieftainY2k/b82e3d4214f8eed93bfc9ef8bfc7e0af to your computer and use it in GitHub Desktop.
Save ChieftainY2k/b82e3d4214f8eed93bfc9ef8bfc7e0af to your computer and use it in GitHub Desktop.
Curl/Wget based website availability checker
#!/usr/bin/bash
#set -e
#set -x
#set -o pipefail
log_message() {
LOGPREFIX="[$(date '+%Y-%m-%d %H:%M:%S')][$(basename ${0%})]"
MESSAGE=$1
echo "$LOGPREFIX $MESSAGE"
}
URL=$1
if [ "${URL}" = "" ]; then
log_message "ERROR: URL must not be empty"
exit 1
fi
URL_HASH=$(echo -n "${URL}" | md5sum | awk '{print $1}')
CACHE_NAMESPACE="/tmp/cwh_${URL_HASH}"
PREV_RESULT_FILE="${CACHE_NAMESPACE}_prev"
CURR_OUTPUT_FILE="${CACHE_NAMESPACE}_curr"
CURR_OUTPUT_FILE_TMP="${CACHE_NAMESPACE}_curr.tmp"
DIFF_OUTPUT_FILE="${CACHE_NAMESPACE}_diff.txt"
touch $PREV_RESULT_FILE
log_message "URL = ${URL} , URL_HASH = ${URL_HASH}, CACHE_NAMESPACE = ${CACHE_NAMESPACE}, PREV_RESULT_FILE = ${PREV_RESULT_FILE}, CURR_OUTPUT_FILE = ${CURR_OUTPUT_FILE}"
DOMAIN=$(echo "$URL" | sed -e 's|^[^/]*//||' -e 's|/.*$||')
MAX_RETRIES=10
RETRY_DELAY=5
echo "" > $CURR_OUTPUT_FILE
#for ((i=1; i<=MAX_RETRIES; i++)); do
# host "${DOMAIN}" > $CURR_OUTPUT_FILE_TMP 2>&1
# EXIT_CODE=$?
# log_message "Resolving hostname, attempt ${i} , exit code = ${EXIT_CODE} , output = $(cat ${CURR_OUTPUT_FILE_TMP})"
# if [ $EXIT_CODE -eq 0 ]; then
# break
# fi
# sleep $RETRY_DELAY
#done
#cat $CURR_OUTPUT_FILE_TMP >> $CURR_OUTPUT_FILE
for ((i=1; i<=MAX_RETRIES; i++)); do
#wget -q -O - "$URL" > $CURR_OUTPUT_FILE_TMP 2>&1
curl --no-progress-meter "$URL" > "$CURR_OUTPUT_FILE_TMP" 2>&1
EXIT_CODE=$?
log_message "Fetching URL, attempt ${i} , exit code = ${EXIT_CODE} , output = $(cat ${CURR_OUTPUT_FILE_TMP})"
if [ $EXIT_CODE -eq 0 ]; then
break
fi
sleep $RETRY_DELAY
done
cat $CURR_OUTPUT_FILE_TMP >> $CURR_OUTPUT_FILE
diff "$PREV_RESULT_FILE" "$CURR_OUTPUT_FILE" > $DIFF_OUTPUT_FILE
DIFF_EXIT_CODE=$?
if [ $DIFF_EXIT_CODE -eq 0 ]; then
log_message "Result did not change"
else
log_message "Result CHANGED"
SUBJECT="Curl alert for ${URL} , result changed at $(date '+%Y-%m-%d %H:%M:%S')"
MESSAGE="Curl result changed for ${URL} , see report for details"
log_message "Sending alerts , SUBJECT = ${SUBJECT} , MESSAGE = ${MESSAGE}"
echo $MESSAGE | mail -s "${SUBJECT}" -A "${DIFF_OUTPUT_FILE}" __________MY_EMAIL___________
mv "$CURR_OUTPUT_FILE" "$PREV_RESULT_FILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment