icinga2-checks/check_curl

131 lines
2.6 KiB
Bash
Executable File

#!/bin/bash
# Define the usage message
usage() {
echo "Usage: $0 -u <url> [-w <warning>] [-c <critical>] [-C <contains>] [-L] [-I] [-H <headers>] [-p] [-R]"
exit 3
}
# Parse the command-line arguments
while getopts "u:w:c:C:H:R:LhIp" opt; do
case $opt in
u)
URL=$OPTARG
;;
w)
WARNING_LEVEL=$OPTARG
;;
c)
CRITICAL_LEVEL=$OPTARG
;;
L)
FOLLOW_REDIRECTS="-L"
;;
C)
CONTAINS=$OPTARG
;;
I)
INSECURE="--insecure"
;;
H)
HEADERS=$OPTARG
;;
p)
PRINT_ONLY=true
;;
R)
RESOLVE="--resolve $OPTARG"
;;
h)
usage
;;
*)
usage
;;
esac
done
WARNING_LEVEL=${WARNING_LEVEL:-1}
CRITICAL_LEVEL=${CRITICAL_LEVEL:-2}
#FOLLOW_REDIRECTS=${FOLLOW_REDIRECTS:-""}
PRINT_ONLY=${PRINT_ONLY:-false}
if [ -z "$URL" ]; then
usage
fi
HEADER_ARGS=""
IFS=',' read -ra values <<<"$HEADERS"
for value in "${values[@]}"; do
HEADER_ARGS+=' -H "'$value'" '
done
CURL_CMD=""
if $PRINT_ONLY; then
echo "curl $CURL_CMD"
exit 3
fi
TMP_ERROR_LOG=$(mktemp)
TMP_RESPONSE=$(mktemp)
RESPONSE=$(curl --output "$TMP_RESPONSE" -s -w "%{http_code}\n%{time_total}" $(echo "${HEADER_ARGS[@]}" | tr -s ' ') $FOLLOW_REDIRECTS $INSECURE $RESOLVE $URL 2>"$TMP_ERROR_LOG")
# shellcheck disable=SC2181
if [ $? -ne 0 ]; then
echo "CRITICAL: curl failed!"
echo "Error log:"
cat "$TMP_ERROR_LOG"
exit 2
fi
rm -rf "$TMP_ERROR_LOG"
RESPONSE_CODE=$(echo "$RESPONSE" | head -n 1)
RESPONSE_TIME=$(printf "%.2f" $(echo "$RESPONSE" | tail -n 1))
OUTPUT_MSG=""
OUTPUT_CODE=0
if [ $RESPONSE_CODE -eq 200 ] && [ "$(echo "$RESPONSE_TIME < $CRITICAL_LEVEL" | bc -l)" -eq 1 ]; then
OUTPUT_MSG="OK: ${RESPONSE_TIME}s - $url."
elif [ $RESPONSE_CODE -eq 200 ] && [ "$(echo "$RESPONSE_TIME < $WARNING_LEVEL" | bc -l)" -eq 1 ]; then
OUTPUT_MSG="WARNING: response time is slow ($RESPONSE_TIME seconds)."
OUTPUT_CODE=1
elif [ $RESPONSE_CODE -eq 200 ]; then
OUTPUT_MSG"CRITICAL: response time is very slow ($RESPONSE_TIME seconds)."
OUTPUT_CODE=2
else
OUTPUT_MSG="CRITICAL: website did not return 200, response was $RESPONSE_CODE code."
OUTPUT_CODE=2
fi
if [[ -n ${CONTAINS+x} ]]; then
if ! grep -q "$CONTAINS" "$TMP_RESPONSE"; then
OUTPUT_MSG+="\nCRITICAL: response did not contain required string!\nFound: $(cat "$TMP_RESPONSE")"
OUTPUT_CODE=2
else
OUTPUT_MSG+="\nOK: response contained required string."
fi
fi
rm -rf "$TMP_RESPONSE"
OUTPUT_MSG+=" | response_time=${RESPONSE_TIME}s;$WARNING_LEVEL;$CRITICAL_LEVEL;0"
case $OUTPUT_CODE in
#0)
# echo "OK: $URL"
# ;;
1)
echo "WARNING: $URL"
;;
2)
echo "CRITICAL: $URL"
;;
*)
echo "CRITICAL: $URL"
;;
esac
echo -e "$OUTPUT_MSG"
exit $OUTPUT_CODE