Advertisement
Guest User

nagios_check_files_age.sh

a guest
Mar 3rd, 2020
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.26 KB | None | 0 0
  1. #!/usr/bin/env bash
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. #     http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15.  
  16. usage() {
  17. echo "Usage: $0 [-c <critical seconds>] [-w <warning seconds>] [-f file pattern with path (required)] [-s strict file check]"
  18. exit 1
  19. }
  20.  
  21. CRIT=
  22. WARN=
  23. FILE_PATTERN=
  24. STRICT_FILE_CHECK=0
  25. # Nagios Exit Codes
  26. OK=0
  27. CRITICAL=2
  28. WARNING=1
  29. UNKNOWN=3
  30.  
  31. while getopts w:c:f:s:h option
  32. do
  33.   case $option
  34.   in
  35.     c) CRIT=$OPTARG;;
  36.     w) WARN=$OPTARG;;
  37.     s) STRICT_FILE_CHECK=1;;
  38.     f) FILE_PATTERN=$OPTARG;;
  39.     h) usage
  40.         exit $UNKNOWN;;
  41.   esac
  42. done
  43. if [[ -z "$FILE_PATTERN" ]]; then
  44.   usage
  45.   exit $UNKNOWN
  46. fi
  47.  
  48. YOUNGEST_FILE_LAST_MODIFIED_SECONDS=99999999
  49. YOUNGEST_FILE_NAME="undefined"
  50. YOUNGEST_FILE_SIZE=99999999
  51. FILES=$( ls $FILE_PATTERN 2>&1)
  52. if [ $? -ne 0 ]; then
  53.    if [ ${STRICT_FILE_CHECK} -eq 1 ]; then
  54.      echo "CRITICAL: No file found matching pattern $FILE_PATTERN"
  55.      exit $CRITICAL
  56.    else
  57.      echo "OK: No file found matching pattern $FILE_PATTERN"
  58.      exit $OK
  59.    fi
  60. fi
  61. for file in $FILES; do
  62.    AGE=$(($(date +%s) - $(date +%s -r "$file")))
  63.    if [ $AGE ]; then
  64.      if [ ${AGE} -lt ${YOUNGEST_FILE_LAST_MODIFIED_SECONDS} ]; then
  65.         YOUNGEST_FILE_LAST_MODIFIED_SECONDS=$AGE
  66.         YOUNGEST_FILE_NAME=$file
  67.      fi
  68.    fi
  69. done
  70.  
  71. YOUNGEST_FILE_SIZE=$(stat -c%s $YOUNGEST_FILE_NAME)
  72. MESSAGE="$YOUNGEST_FILE_NAME is $YOUNGEST_FILE_LAST_MODIFIED_SECONDS seconds old and $YOUNGEST_FILE_SIZE bytes.[w=$WARN , c=$CRIT s]"
  73.  
  74. if [ -n "$CRIT" ] && [ ${YOUNGEST_FILE_LAST_MODIFIED_SECONDS} -ge ${CRIT} ]; then
  75.    echo "FILE_AGE CRITICAL: $MESSAGE"
  76.    exit $CRITICAL
  77. fi
  78.  
  79. if [ -n "$WARN" ] && [ ${YOUNGEST_FILE_LAST_MODIFIED_SECONDS} -ge ${WARN} ]; then
  80.    echo "FILE_AGE WARNING: $MESSAGE"
  81.    exit $WARNING
  82. fi
  83.  
  84. echo "FILE_AGE OK: $MESSAGE"
  85. exit $OK
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement