pax_global_header 0000666 0000000 0000000 00000000064 13431537440 0014516 g ustar 00root root 0000000 0000000 52 comment=0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/ 0000775 0000000 0000000 00000000000 13431537440 0022151 5 ustar 00root root 0000000 0000000 nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/.gitignore 0000664 0000000 0000000 00000000031 13431537440 0024133 0 ustar 00root root 0000000 0000000 /.project
/.pydevproject
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/.gitlab-ci.yml 0000664 0000000 0000000 00000000544 13431537440 0024610 0 ustar 00root root 0000000 0000000 image: buildpack-deps:stretch
stages:
- publish
github_push:
stage: publish
script:
- git push --force https://${GITHUB_USR}:${GITHUB_PWD}@github.com/ikus060/nagios-plugins.git refs/remotes/origin/${CI_COMMIT_REF_NAME}:refs/heads/${CI_COMMIT_REF_NAME}
- git push https://${GITHUB_USR}:${GITHUB_PWD}@github.com/ikus060/nagios-plugins.git --tags
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/Jenkinsfile 0000664 0000000 0000000 00000000660 13431537440 0024337 0 ustar 00root root 0000000 0000000 pipeline {
environment {
GITHUB = credentials("github")
}
agent any
stages {
stage('GitHubPush') {
steps {
sh "git push --force https://${GITHUB}@github.com/ikus060/nagios-plugins.git refs/remotes/origin/${BRANCH_NAME}:refs/heads/${BRANCH_NAME}"
sh "git push https://${GITHUB}@github.com/ikus060/nagios-plugins.git --tags"
}
}
}
}
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/README.md 0000664 0000000 0000000 00000000751 13431537440 0023433 0 ustar 00root root 0000000 0000000 # Nagios Plugins
This is my private collection of nagios plugins. I've found some of them on
the web and I modify them to fit me need. The other I wrote from scratch using
nagios skeleton.
I'm making this repository available to the public to share my work.
# License
Each plugin have it own license. Have a look at the header file.
# Help & Support
If you need help or have comment about one of the plugin, I invite you to
write an email to support@patrikdufresne.com nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_by_ssh_ikus 0000775 0000000 0000000 00000012031 13431537440 0025553 0 ustar 00root root 0000000 0000000 #! /bin/bash
#
# Wrapper arround check_by_ssh to avoid returning CRITICAL when the plugin timeout.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2012 Patrik Dufresne
# Last modified 2012-11-02
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=0.2
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
printf "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
SSH="ssh"
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$PROGNAME"
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s -H -C [-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-C, --command Command to execute on the remote machine.
-h, --help Display this message.
-H, --hostname Host name, IP Address.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
if [ $# -eq 0 ] ; then
usage
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$PROGNAME" --options "-h,-V,-v,-t:,-H:,-C" \
--longoptions "help,version,verbose,verbosity:,timeout:,hostname:,command:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare -i TIMELIMIT=10
declare -i VERBOSITY=0
declare HOST
declare COMMAND
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-H | --hostname)
shift
HOST=$1;;
-C | --command)
shift
COMMAND=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
if [ -z "$HOST" ]; then
printf "%s: You must provide a host name\n" "$PROGNAME"
cleanup $STATE_UNKNOWN
fi
if [ -z "$COMMAND" ]; then
printf "%s: No remotecmd\n" "$PROGNAME"
cleanup $STATE_UNKNOWN
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
(
((t = $TIMELIMIT))
while ((t > 0)); do
sleep 1
kill -0 $$ || exit 0
((t -= 1))
done
kill -s USR1 $$ || exit 0
sleep 2
kill -- -$$
) 2>/dev/null >/dev/null &
OUT=`$SSH "$HOST" "$COMMAND" 2>&1`
STATE=$?
trap - USR1
printf "$OUT"
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_cpu_ikus 0000775 0000000 0000000 00000014672 13431537440 0025070 0 ustar 00root root 0000000 0000000 #!/bin/bash
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# Originaly taken from:
# https://exchange.nagios.org/directory/Plugins/System-Metrics/CPU-Usage-and-Load/check_cpu-2Esh-(matejunkie)/details
#
# Modified by:
# 2016-01-21 Patrik Dufresne Service Logiciel inc.
PROGNAME=`basename $0`
VERSION="Version 1.1,"
AUTHOR="2016, Mike Adolphs (http://www.matejunkie.com/)"
ST_OK=0
ST_WR=1
ST_CR=2
ST_UK=3
interval=2
print_version() {
echo "$VERSION $AUTHOR"
}
print_help() {
print_version $PROGNAME $VERSION
echo ""
echo "$PROGNAME is a Nagios plugin to monitor CPU utilization. It makes"
echo "use of /proc/stat and calculates it through Jiffies rather than"
echo "using another frontend tool like iostat or top."
echo "When using optional warning/critical thresholds all values except"
echo "idle are aggregated and compared to the thresholds. There's"
echo "currently no support for warning/critical thresholds for specific"
echo "usage parameters."
echo ""
echo "$PROGNAME [-i/--interval] [-w/--warning] [-c/--critical]"
echo ""
echo "Options:"
echo " --interval|-i)"
echo " Defines the pause between the two times /proc/stat is being"
echo " parsed. Higher values could lead to more accurate result."
echo " Default is: 1 second"
echo " --warning|-w)"
echo " Sets a warning level for CPU user. Default is: off"
echo " --critical|-c)"
echo " Sets a critical level for CPU user. Default is: off"
exit $ST_UK
}
while test -n "$1"; do
case "$1" in
--help|-h)
print_help
exit $ST_UK
;;
--version|-v)
print_version $PROGNAME $VERSION
exit $ST_UK
;;
--interval|-i)
interval=$2
shift
;;
--warning|-w)
warn=$2
shift
;;
--critical|-c)
crit=$2
shift
;;
*)
echo "Unknown argument: $1"
print_help
exit $ST_UK
;;
esac
shift
done
val_wcdiff() {
if [ ${warn} -gt ${crit} ]
then
wcdiff=1
fi
}
get_cpuvals() {
DATA=$(grep -m1 '^cpu' /proc/stat)
tmp1_cpu_user=$((awk '{print $2}') <<< """$DATA""")
tmp1_cpu_nice=$((awk '{print $3}') <<< """$DATA""")
tmp1_cpu_sys=$((awk '{print $4}') <<< """$DATA""")
tmp1_cpu_idle=$((awk '{print $5}') <<< """$DATA""")
tmp1_cpu_iowait=$((awk '{print $6}') <<< """$DATA""")
tmp1_cpu_irq=$((awk '{print $7}') <<< """$DATA""")
tmp1_cpu_softirq=$((awk '{print $8}') <<< """$DATA""")
tmp1_cpu_total=`expr $tmp1_cpu_user + $tmp1_cpu_nice + $tmp1_cpu_sys + \
$tmp1_cpu_idle + $tmp1_cpu_iowait + $tmp1_cpu_irq + $tmp1_cpu_softirq`
sleep $interval
DATA=$(grep -m1 '^cpu' /proc/stat)
tmp2_cpu_user=$((awk '{print $2}') <<< """$DATA""")
tmp2_cpu_nice=$((awk '{print $3}') <<< """$DATA""")
tmp2_cpu_sys=$((awk '{print $4}') <<< """$DATA""")
tmp2_cpu_idle=$((awk '{print $5}') <<< """$DATA""")
tmp2_cpu_iowait=$((awk '{print $6}') <<< """$DATA""")
tmp2_cpu_irq=$((awk '{print $7}') <<< """$DATA""")
tmp2_cpu_softirq=$((awk '{print $8}') <<< """$DATA""")
tmp2_cpu_total=`expr $tmp2_cpu_user + $tmp2_cpu_nice + $tmp2_cpu_sys + \
$tmp2_cpu_idle + $tmp2_cpu_iowait + $tmp2_cpu_irq + $tmp2_cpu_softirq`
diff_cpu_user=`echo "${tmp2_cpu_user} - ${tmp1_cpu_user}" | bc -l`
diff_cpu_nice=`echo "${tmp2_cpu_nice} - ${tmp1_cpu_nice}" | bc -l`
diff_cpu_sys=`echo "${tmp2_cpu_sys} - ${tmp1_cpu_sys}" | bc -l`
diff_cpu_idle=`echo "${tmp2_cpu_idle} - ${tmp1_cpu_idle}" | bc -l`
diff_cpu_iowait=`echo "${tmp2_cpu_iowait} - ${tmp1_cpu_iowait}" | bc -l`
diff_cpu_irq=`echo "${tmp2_cpu_irq} - ${tmp1_cpu_irq}" | bc -l`
diff_cpu_softirq=`echo "${tmp2_cpu_softirq} - ${tmp1_cpu_softirq}" \
| bc -l`
diff_cpu_total=`echo "${tmp2_cpu_total} - ${tmp1_cpu_total}" | bc -l`
cpu_user=`echo "scale=2; (1000*${diff_cpu_user}/${diff_cpu_total}+5)/10" \
| bc -l | sed 's/^\./0./'`
cpu_nice=`echo "scale=2; (1000*${diff_cpu_nice}/${diff_cpu_total}+5)/10" \
| bc -l | sed 's/^\./0./'`
cpu_sys=`echo "scale=2; (1000*${diff_cpu_sys}/${diff_cpu_total}+5)/10" \
| bc -l | sed 's/^\./0./'`
cpu_idle=`echo "scale=2; (1000*${diff_cpu_idle}/${diff_cpu_total}+5)/10" \
| bc -l | sed 's/^\./0./'`
cpu_iowait=`echo "scale=2; (1000*${diff_cpu_iowait}/${diff_cpu_total}+5)\\
/10" | bc -l | sed 's/^\./0./'`
cpu_irq=`echo "scale=2; (1000*${diff_cpu_irq}/${diff_cpu_total}+5)/10" \
| bc -l | sed 's/^\./0./'`
cpu_softirq=`echo "scale=2; (1000*${diff_cpu_softirq}/${diff_cpu_total}\\
+5)/10" | bc -l | sed 's/^\./0./'`
cpu_total=`echo "scale=2; (1000*${diff_cpu_total}/${diff_cpu_total}+5)\\
/10" | bc -l | sed 's/^\./0./'`
cpu_usage=`echo "(${cpu_user}+${cpu_nice}+${cpu_sys}+${cpu_iowait}+\\
${cpu_irq}+${cpu_softirq})/1" | bc`
}
do_output() {
output="user: ${cpu_user}%, nice: ${cpu_nice}%, sys: ${cpu_sys}%, \
iowait: ${cpu_iowait}%, irq: ${cpu_irq}%, softirq: ${cpu_softirq}% \
idle: ${cpu_idle}%"
}
do_perfdata() {
perfdata="user=${cpu_user}% nice=${cpu_nice}% sys=${cpu_sys}% \
softirq=${cpu_softirq}% iowait=${cpu_iowait}% irq=${cpu_irq}% \
idle=${cpu_idle}%"
}
if [ -n "$warn" -a -n "$crit" ]
then
val_wcdiff
if [ "$wcdiff" = 1 ]
then
echo "Please adjust your warning/critical thresholds. The warning\\
must be lower than the critical level!"
exit $ST_UK
fi
fi
get_cpuvals
do_output
do_perfdata
if [ -n "$warn" -a -n "$crit" ]
then
if [ "$cpu_usage" -ge "$warn" -a "$cpu_usage" -lt "$crit" ]
then
echo "WARNING - ${output} | ${perfdata}"
exit $ST_WR
elif [ "$cpu_usage" -ge "$crit" ]
then
echo "CRITICAL - ${output} | ${perfdata}"
exit $ST_CR
else
echo "OK - ${output} | ${perfdata}"
exit $ST_OK
fi
else
echo "OK - ${output} | ${perfdata}"
exit $ST_OK
fi
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_debian_release_ikus 0000775 0000000 0000000 00000023373 13431537440 0027221 0 ustar 00root root 0000000 0000000 #!/bin/bash
###
#
# Verify the debian release.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-10-30
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
VERSION=1.0
AUTHOR="Patrik Dufresne"
SERVICE="DEBIAN"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
BC=/usr/bin/bc
if [ ! -x "$BC" ] ; then
echo "$BC utility is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s \
-w -c \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-w, --warning=val Set the debian release version warning threshold.
-c, --critical=val Set the debian release critical threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 3 ] ; then
shopt -o -s xtrace
fi
# Check that the thresholds provided are valid strings
if [ -z "$WARNING" -o -z "$CRITICAL" ] ; then
range_help
else
# positive values only
WARNFORMAT=`echo "$WARNING" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
CRITFORMAT=`echo "$CRITICAL" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
OK=$(( $WARNFORMAT + $CRITFORMAT ))
if [ $OK -lt 2 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
VALUE=$(cat /etc/debian_version)
trap - USR1
function check_value {
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ $(echo "$START <= $2 && $2 <= $END" | bc) -eq 1 ] ; then
return 1
fi
elif [ $(echo "$2 < $START || $END < $2" | bc) -eq 1 ] ; then
return 1
fi
return 0
}
# check conditions - yes this is ugly, blame BASH. If you want to blame me, please provide a cleaner way that is as fast or faster
check_value "$CRITICAL" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
else
check_value "$WARNING" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
else
STATE=$STATE_OK
fi
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="v$VALUE ($(uname -m -r))"
case $STATE in
$STATE_OK)
printf "%s OK: %s\n" "$SERVICE" "$OUT $PERF";;
$STATE_WARNING)
printf "%s WARNING: %s\n" "$SERVICE" "$OUT $PERF";;
$STATE_CRITICAL)
printf "%s CRITICAL: %s\n" "$SERVICE" "$OUT $PERF";;
$STATE_UNKNOWN)
printf "%s UNKNOWN: %s\n" "$SERVICE" "$OUT $PERF";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_dyndns_ikus 0000775 0000000 0000000 00000017577 13431537440 0025607 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
# Nagios plugin skeleton
# http://nagiosplug.sourceforge.net/developer-guidelines.html
#
# Check dns resolution of the hostname spacified agains the current ip.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2012 Patrik Dufresne
# Last modified 2012-11-02
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="DYNDNS"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
CURL=/usr/bin/curl
if [ ! -x "$CURL" ] ; then
echo "The utility $CURL is not installed. Exiting."
cleanup $STATE_UNKNOWN
fi
HOST=/usr/bin/host
if [ ! -x "$HOST" ] ; then
echo "The utility host is not installed. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s -H \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-H, --hostname Define the dns name to verify.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
if [ $# -eq 0 ] ; then
usage
fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-t:,-H:" --longoptions "help,version,verbose,verbosity:,timeout:,hostname:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-H | --hostname)
shift
HOSTNAME=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Check that sensor is provided
if [ -z "$HOSTNAME" ] ; then
usage
fi
# Get the hostname value
DYNDNS_IP=$($CURL --max-time $TIMELIMIT checkip.dyndns.org 2>&1)
IP_STATE=$?
if [ $? -eq 0 ]
then
DYNDNS_IP=`expr "$DYNDNS_IP" : '^.*Current IP Address: \([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*$'`
IP_STATE=$?
fi
HOSTNAME_IP=`$HOST "$HOSTNAME"`
HOST_SATE=$?
if [ $? -eq 0 ]
then
HOSTNAME_IP=`expr "$HOSTNAME_IP" : '.* has address \([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$'`
HOST_SATE=$?
fi
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
# Check the state
if [ $IP_STATE -ne 0 ] ; then
STATE=$STATE_UNKNOWN
OUT="Cannot parse result from checkip.dyndns.org"
else
if [ $HOST_SATE -ne 0 ] ; then
STATE=$STATE_CRITICAL
OUT="Could not resolve hostname $HOSTNAME"
else
if [ "$HOSTNAME_IP" == "$DYNDNS_IP" ] ; then
STATE=$STATE_OK
OUT="hostname resolved to $HOSTNAME_IP"
else
STATE=$STATE_CRITICAL
OUT="hostname resolution doesn't matches : $HOSTNAME_IP <> $DYNDNS_IP"
fi
fi
fi
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_file_content_ikus 0000775 0000000 0000000 00000030357 13431537440 0026750 0 ustar 00root root 0000000 0000000 #!/bin/bash
#
# Check and validate file content.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-08-14
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# you probably want to uncomment the following lines while developing
#shopt -o -s xtrace
# if you turn this on, then you have to alter the check_value calls to be able to check $?
#shopt -o -s errexit
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="CONTENT"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# provide detailed explanations of the command line syntax
function longhelp {
printf " %s %s for Nagios - Usage %s -f [-R] [-i ] \
[-e [] [-w ] [-c ] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-f, --file Define the file to search in.
-R, --recursive Recursive search.
-i, --include=val The regex pattern (can add multiple).
-e, --exclude=val The regex pattern to exclude (can add multiple)
-w, --warning=val Treshold for number of lines.
-c, --critial=val Threshold for number of lines.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:,-f:,-R,-i:,-e:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:,file:,recursive,include:,exclude:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
declare FILE
declare -a INCLUDES
declare -a EXCLUDES
declare -i RECURSIVE
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-f | --file)
shift
FILE=$1;;
-R | --recursive)
RECURSIVE=1;;
-i | --include)
shift
INCLUDES+=('-e')
INCLUDES+=("$1");;
-e | --exclude)
shift
EXCLUDES+=('-e')
EXCLUDES+=("$1");;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# Check that the thresholds provided are valid strings
function check_range {
# # positive values only
if [ ! -z "$1" ] ; then
FORMAT=`echo "$1" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $FORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
}
if [ ! -z "$WARNING" ]; then
check_range "$WARNING"
fi
if [ ! -z "$CRITICAL" ]; then
check_range "$CRITICAL"
fi
# Check if file argument is provided
if [ -z "$FILE" ]; then
echo "CRITICAL - no file argument (-f) given."
cleanup $STATE_CRITICAL
fi
if [ -z "$INCLUDES" -a -z "$EXCLUDES" ]; then
echo "CRITICAL - includes (-i) or excludes (-e) pattern(s) required."
cleanup $STATE_CRITICAL
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Check if file exists
if [ ! -e "$FILE" ]; then
echo "CRITICAL - File $FILE not found!"
cleanup $STATE_CRITICAL
fi
if [ "$RECURSIVE" == "1" ]; then
ARGS="-R "
fi
# Count number of matches
if [ -z "$EXCLUDES" ]; then
NBLINE=$(grep -E $ARGS "${INCLUDES[@]}" "$FILE" 2>/dev/null | wc -l)
elif [ -z "$INCLUDES" ]; then
NBLINE=$(grep -v -E $ARGS "${EXCLUDES[@]}" "$FILE" 2>/dev/null | wc -l)
else
NBLINE=$(grep -E $ARGS "${INCLUDES[@]}" "$FILE" 2>/dev/null | grep -c -v -E "${EXCLUDES[@]}" 2>/dev/null)
fi
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# check conditions - yes this is ugly, blame BASH.
# If you want to blame me, please provide a cleaner way that is as fast or faster
STATE=$STATE_OK
check_value "$CRITICAL" "$NBLINE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
# Check warning treshold
if [ $STATE -ne $STATE_CRITICAL ]; then
check_value "$WARNING" "$NBLINE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
fi
OUT="$FILE found $NBLINE line(s) | count=$NBLINE"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_file_count_ikus 0000775 0000000 0000000 00000026653 13431537440 0026432 0 ustar 00root root 0000000 0000000 #!/bin/bash
#
# Check how many files exists
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2018 Patrik Dufresne
# Last modified 2018-08-23
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# you probably want to uncomment the following lines while developing
#shopt -o -s xtrace
# if you turn this on, then you have to alter the check_value calls to be able to check $?
#shopt -o -s errexit
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="FILES"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# provide detailed explanations of the command line syntax
function longhelp {
printf " %s %s for Nagios - Usage %s -f [-R] \
[-w ] [-c ] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-p, --path Define the path where to search for files.
-R, --recursive Recursive search.
-w, --warning=val Treshold for number of files.
-c, --critial=val Threshold for number of files.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:,-p:,-R" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:,path:,recursive" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
declare FILE
declare -a INCLUDES
declare -a EXCLUDES
declare -i RECURSIVE
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-p | --path)
shift
FILE=$1;;
-R | --recursive)
RECURSIVE=1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# Check that the thresholds provided are valid strings
function check_range {
# # positive values only
if [ ! -z "$1" ] ; then
FORMAT=`echo "$1" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $FORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
}
if [ ! -z "$WARNING" ]; then
check_range "$WARNING"
fi
if [ ! -z "$CRITICAL" ]; then
check_range "$CRITICAL"
fi
# Check if file argument is provided
if [ -z "$FILE" ]; then
echo "CRITICAL - no path argument (-p) given"
cleanup $STATE_CRITICAL
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Check if file exists
if [ ! -e "$FILE" ]; then
echo "CRITICAL - Path $FILE not found!"
cleanup $STATE_CRITICAL
fi
if [ "$RECURSIVE" != "1" ]; then
ARGS="-maxdepth 0 "
fi
# Count number of matches
NBFILES=$(find "$FILE" $ARGS -type f 2>/dev/null | wc -l)
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# check conditions - yes this is ugly, blame BASH.
# If you want to blame me, please provide a cleaner way that is as fast or faster
STATE=$STATE_OK
check_value "$CRITICAL" "$NBFILES"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
# Check warning treshold
if [ $STATE -ne $STATE_CRITICAL ]; then
check_value "$WARNING" "$NBFILES"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
fi
OUT="found $NBFILES files(s) | count=$NBFILES"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_gmailunread 0000775 0000000 0000000 00000012613 13431537440 0025527 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
import imaplib,getopt,sys
#
# Copyright 2012 Peter Dyson
# https://github.com/geekpete/nagiosplugins/
#
# Licensed under the GNU General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
################################################################################
#
# check_gmailunread.py
# Nagios plugin to check number of unread emails in a gmail account
#
# This script logs into a given gmail account and counts the unread emails.
# It will then alert based on the WARN and CRITICAL thresholds.
#
################################################################################
### Define required nagios script settings.
# define script name.
scriptName=sys.argv[0]
# define script version.
scriptVersion = "v0.1.0"
# Nagios plugin exit codes
STATE_OK = 0
STATE_WARNING = 1
STATE_CRITICAL = 2
STATE_UNKNOWN = 3
# Clear default variable states
nagiosState = ""
gmailUser = ""
gmailPassword = ""
#####
class Usage(Exception):
def __init__(self, err):
self.msg = err
def usage():
print "Usage: check_gmailunread.py -u email_user -p email_password -w warn_unread -c crit_unread"
print " check_gmailunread.py -h for detailed help"
print " check_gmailunread.py -V for version information"
def detailedUsage():
print "Nagios plugin to check how many unread emails are in a gmail account"
print
usage()
print
print "Options:"
print " -h"
print " Print this help message."
print " -V"
print " Print version information then exit."
print " -u gmail_user"
print " User name of the gmail account."
print " For google enterprise accounts use the full email address:"
print " eg, your.email@yourcompany.com"
print " -p gmail_password "
print " Password of the gmail account."
print " -w warn_count"
print " Warning threshold count for unread emails."
print " -c crit_count"
print " Critical threshold count for unread emails."
print
# parse the command line switches and arguments
try:
try:
opts, args = getopt.getopt(sys.argv[1:], "hVH:u:p:w:c:v", ["help", "output="])
except getopt.GetoptError, err:
# print help information and exit:
raise Usage(err)
except Usage, err:
print >>sys.stderr, err.msg
usage()
sys.exit(STATE_UNKNOWN)
# gather values from given parameter switches
for o, a in opts:
if o == "-w":
unreadWARNING = int(a)
elif o == "-c":
unreadCRITICAL = int(a)
elif o == "-u":
gmailUser = a
elif o == "-p":
gmailPassword = a
elif o in ("-V","-v","--version"):
print scriptName + " " + scriptVersion
usage()
sys.exit()
elif o in ("-h", "--help"):
detailedUsage()
sys.exit()
else:
assert False, "unhandled option"
# Check to see if a host has been specified, throw an error if not.
if gmailUser=="":
print "Error: no gmail user specified."
usage()
sys.exit()
elif gmailPassword=="":
print "Error: no gmail password specified."
usage()
sys.exit()
elif unreadWARNING=="":
print "Error: no unread WARNING threshhold specified."
usage()
sys.exit()
elif unreadCRITICAL=="":
print "Error: no unread CRITICAL threshold specified."
usage()
sys.exit()
# open an SSL imap4 connection to gmail, fail if unsuccessful
try:
# Open imap4 conection to imap.gmail.com.
gmailconnection = imaplib.IMAP4_SSL('imap.gmail.com',993)
except Exception:
print "UNKNOWN: error connecting to imap.gmail.com on tcp port 993"
sys.exit(3)
# try to use the gmail login on the newly opened imap connection, fail if unsuccessful
try:
# log in with gmail account and password
gmailconnection.login(gmailUser,gmailPassword)
except Exception:
print "UKNOWN: error authenticating against opened gmail imap connection with provided credentials"
sys.exit(3)
# attempt to count the unread emails for this gmail account now that we've logged in
try:
# log in with gmail account and password
gmailconnection.select()
unreadEmailCount=int(len(gmailconnection.search(None, 'UnSeen')[1][0].split()))
except Exception:
print "UKNOWN: error reading number of unread emails for gmail account %s" % gmailUser
sys.exit(3)
# check the response time of the url
if unreadEmailCount >= unreadCRITICAL:
checkResult="CRITICAL"
nagiosState=STATE_CRITICAL
elif unreadEmailCount >= unreadWARNING:
checkResult="WARNING"
nagiosState=STATE_WARNING
else:
# otherwise it's ok
checkResult="OK"
nagiosState=STATE_OK
# display output of the metrics and any warnings
print "Unread email count for %s is %d: %s" % (gmailUser, unreadEmailCount, checkResult)
sys.exit(nagiosState)
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_hw_ikus 0000775 0000000 0000000 00000014360 13431537440 0024711 0 ustar 00root root 0000000 0000000 #!/bin/bash
###
#
# Repport hardware info
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-10-30
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
VERSION=1.0
AUTHOR="Patrik Dufresne"
SERVICE="HW"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 3 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Get motherboard info
BOARDVENDOR=""
if [ -r /sys/devices/virtual/dmi/id/board_vendor ]; then
BOARDVENDOR=$(cat /sys/devices/virtual/dmi/id/board_vendor)
fi
BOARDNAME=""
if [ -r /sys/devices/virtual/dmi/id/board_name ]; then
BOARDNAME=$(cat /sys/devices/virtual/dmi/id/board_name)
elif [ $(grep -c 'Hardware' /proc/cpuinfo) -gt 0 ]; then
DATA=$(grep -m 1 'Hardware' /proc/cpuinfo)
BOARDNAME=${DATA##*: }
fi
# Get CPU info
DATA=$(grep -m 1 'model name' /proc/cpuinfo)
CPU=${DATA##*: }
# Get Disk info
DISK_DATA=$(ls /dev/sd? | xargs -I {} sh -c 'echo -n "Disk {}: "; sudo smartctl -a {} | egrep "(Device Model:|Serial Number:)" | sed "s/Device Model: *//g;s/Serial Number: */SN: /g" | tr "\n" " " ; echo ')
trap - USR1
STATE=$STATE_OK
OUT="board: $BOARDVENDOR $BOARDNAME, cpu: $CPU"
LONG_OUT="Board: $BOARDVENDOR $BOARDNAME
Cpu: $CPU
$DISK_DATA"
case $STATE in
$STATE_OK)
printf "%s OK: %s\n%s\n" "$SERVICE" "$OUT" "$LONG_OUT";;
$STATE_WARNING)
printf "%s WARNING: %s\n%s\n" "$SERVICE" "$OUT" "$LONG_OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL: %s\n%s\n" "$SERVICE" "$OUT" "$LONG_OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN: %s\n%s\\n" "$SERVICE" "$OUT" "$LONG_OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_ipmi_sensor_ikus 0000775 0000000 0000000 00000027023 13431537440 0026622 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
# Check hardware sensor using `ipmitool sensor` command line provided by lm-sensors
#
# Required the following sudoers
#
# nagios ALL=(ALL) NOPASSWD: /usr/bin/ipmitool sensor
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-02-22
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# you probably want to uncomment the following lines while developing
#shopt -o -s xtrace
# if you turn this on, then you have to alter the check_value calls to be able to check $?
#shopt -o -s errexit
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="SENSOR"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
IPMITOOL=/usr/bin/ipmitool
if [ ! -x "$IPMITOOL" ] ; then
echo "$IPMITOOL is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s -s \
-w -c \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-s, --sensor Set the sensor to monitor
-w, --warning=val Set the warning percentage threshold.
-c, --critical=val Set the critical percentage threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
if [ $# -eq 0 ] ; then
usage
fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:,-s:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:,sensor:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-s | --sensor)
shift
SENSOR=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Check that sensor is provided
if [ -z "$SENSOR" ] ; then
usage
fi
# Check that the thresholds provided are valid strings
if [ -z "$WARNING" -o -z "$CRITICAL" ] ; then
range_help
else
# positive values only
WARNFORMAT=`echo "$WARNING" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
CRITFORMAT=`echo "$CRITICAL" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
OK=$(( $WARNFORMAT + $CRITFORMAT ))
if [ $OK -lt 2 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
# Get the sensor's value
LINE=`sudo -n $IPMITOOL sensor | grep "$SENSOR" | head -n 1`
if [[ -z "$LINE" ]]; then
#Given sensor doesn't exists
printf "UNKNOWN - Given sensors $SENSOR doesn't exists.\n"
cleanup $STATE_UNKNOWN
fi
VALUE=`echo $(echo $LINE | cut -d '|' -f 2 | sed 's/\s\([0-9]*\).*/\1/')`
VALUE_UNIT=`echo $(echo $LINE | cut -d '|' -f 3)`
if [[ $VALUE_UNIT == "degrees C" ]]; then
VALUE_UNIT="°C"
fi
SENSOR=`echo $(echo $LINE | cut -d '|' -f 1 | sed 's/\s/_/')`
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# check conditions - yes this is ugly, blame BASH. If you want to blame me, please provide a cleaner way that is as fast or faster
check_value "$CRITICAL" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
else
check_value "$WARNING" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
else
STATE=$STATE_OK
fi
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="$SENSOR $VALUE $VALUE_UNIT | $SENSOR=${VALUE};$WARNING;$CRITICAL"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_memory_ikus 0000775 0000000 0000000 00000030222 13431537440 0025576 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
# This plugin monitor the memory usage for Linux operating system. This memory take
# consideration of ZFS arcstats memory usages.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-03-06
#
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="MEMORY"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s \
[-w <% warning memory usage>] [-c <% critical memory usage>] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-w, --warning=val Set the warning memory usage threshold.
-c, --critical=val Set the critical memory usage threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
#if [ $# -eq 0 ] ; then
# usage
#fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-t:,-w:,-c:" \
--longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
function check_range {
# # positive values only
if [ ! -z "$1" ] ; then
WARNFORMAT=`echo "$1" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $WARNFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
if [ ! -z "$2" ] ; then
CRITFORMAT=`echo "$2" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $CRITFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
}
check_range "$WARNING" "$CRITICAL"
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Get the memory usages.
DATA=`cat /proc/meminfo`
if [ $VERBOSITY -gt 2 ] ; then
echo "$DATA"
fi
TOTAL_KB=`echo "$DATA" | egrep '^MemTotal' | awk '{print $2;}'`
FREE_KB=`echo "$DATA" | egrep '^MemFree' | awk '{print $2;}'`
BUFFERS_KB=`cat /proc/meminfo | egrep '^(Buffers|SReclaimable)' | awk '{s+=$2} END {print s}'`
CACHE_KB=`cat /proc/meminfo | egrep '^Cached' | awk '{s+=$2} END {print s}'`
SWTOTAL_KB=`echo "$DATA" | egrep '^SwapTotal' | awk '{print $2;}'`
SWFREE_KB=`echo "$DATA" | egrep '^SwapFree' | awk '{print $2;}'`
SWCACHE_KB=`echo "$DATA" | egrep '^SwapCached' | awk '{print $2;}'`
# Get arcstats memory usage.
ARC_KB=0
if [ -e "/proc/spl/kstat/zfs/arcstats" ]; then
ARC=`egrep '^size' /proc/spl/kstat/zfs/arcstats | awk '{print $3;}'`
ARC_KB=`expr $ARC / 1024`
fi
# Compute usage
USED_KB=`expr $TOTAL_KB - $FREE_KB - $BUFFERS_KB - $CACHE_KB - $ARC_KB`
SWUSED_KB=`expr $SWTOTAL_KB - $SWFREE_KB - $SWCACHE_KB`
# compute value in MiB
TOTAL_MB=`expr $TOTAL_KB / 1024`
FREE_MB=`expr $FREE_KB / 1024`
BUFFERS_MB=`expr $BUFFERS_KB / 1024`
CACHE_MB=`expr $CACHE_KB / 1024`
SWTOTAL_MB=`expr $SWTOTAL_KB / 1024`
SWFREE_MB=`expr $SWFREE_KB / 1024`
USED_MB=`expr $USED_KB / 1024`
SWCACHE_MB=`expr $SWCACHE_KB / 1024`
SWUSED_MB=`expr $SWUSED_KB / 1024`
ARC_MB=`expr $ARC_KB / 1024`
# Compute percentage value
USED=`expr 100 '*' $USED_KB / $TOTAL_KB`
SWUSED=0
if [ "$SWTOTAL_KB" -gt "0" ]; then
SWUSED=`expr 100 '*' $SWUSED_KB / $SWTOTAL_KB`
fi
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range all ranges are inclusive
# of endpoints so we use less than or equal on the inside and just less
# than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# Check critical threshold
STATE=$STATE_OK
check_value "$CRITICAL" "$USED"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
# Check warning treshold
if [ $STATE -ne $STATE_CRITICAL ]; then
check_value "$WARNING" "$USED"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
fi
OUT="Usage: real $USED% ($USED_MB/$TOTAL_MB MB), buffer: $BUFFERS_MB MB, cache: $CACHE_MB MB, arc-cache: $ARC_MB MB, swap: $SWUSED ($SWUSED_MB/$SWTOTAL_MB MB)| utilisation=${USED}% buffer=${BUFFERS_MB}MB cached=${CACHE_MB}MB arc-cache=${ARC_MB}MB swap=${SWUSED_MB}MB"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_nut_ikus 0000775 0000000 0000000 00000034026 13431537440 0025102 0 ustar 00root root 0000000 0000000 #! /bin/bash
#
# This plugin check the state of a UPS using nut (Network UPS Tools).
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-02-15
# Please send all comments, suggestions, bugs and patches to
# (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="UPS"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
UPSC=/bin/upsc
if [ ! -x "$UPSC" ] ; then
echo "upsc is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s \
--name
[-o ] [-O ] \
[-b ] [-B ] \
[-l ] [-L ] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-n,--name Set the name of the ups to query data for.
--o, --warning-voltage=val Set the warning output voltage threshold.
--O, --critical-voltage=val Set the critical output voltage threshold.
--b, --warning-battery=val Set the warning percentage battery capacity threshold.
--B, --critical-battery=val Set the critical percentage battery capacity threshold.
--l, --warning-load=val Set the warning load percentage threshold.
--L, --critical-load=val Set the critical load percentage threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
if [ $# -eq 0 ] ; then
usage
fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-t:,-o:,-O:,-b:,-B:,-l:,-L:,-n:" \
--longoptions "help,version,verbose,verbosity:,warning-voltage:,warning-battery:,warning-load:,critical-voltage:,critical-battery:,critical-load:,name:,timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-n | --name)
shift
UPS_NAME=$1;;
-o | --warning-voltage)
shift
VOLTAGE_WARNING=$1;;
-b | --warning-battery)
shift
BATTERY_WARNING=$1;;
-l | --warning-load)
shift
LOAD_WARNING=$1;;
-O | --critical-voltage)
shift
VOLTAGE_CRITICAL=$1;;
-B | --critical-battery)
shift
BATTERY_CRITICAL=$1;;
-L | --critical-load)
shift
LOAD_CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
function check_range {
# # positive values only
if [ ! -z "$1" ] ; then
WARNFORMAT=`echo "$1" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $WARNFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
if [ ! -z "$2" ] ; then
CRITFORMAT=`echo "$2" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $CRITFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
}
if [ -z "$UPS_NAME" ]; then
usage
fi
check_range "$VOLTAGE_WARNING" "$VOLTAGE_CRITICAL"
check_range "$BATTERY_WARNING" "$BATTERY_CRITICAL"
check_range "$LOAD_WARNING" "$LOAD_CRITICAL"
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Get the sensor's value
DATA="$($UPSC $UPS_NAME 2>&1)"
if [ $VERBOSITY -gt 2 ] ; then
echo "$DATA"
fi
if grep ups.status > /dev/null <<< """$DATA"""; then
UPSSTATE=$((grep ups.status | cut -d ' ' -f 2) <<< "$DATA")
else
UPSSTATE="$DATA"
fi
if [ "$UPSSTATE" != "Lost Communication" ]; then
OUT_VOLTAGE=$((grep 'output.voltage:' | cut -d ' ' -f 2) <<< """$DATA""")
OUT_FREQ=$((grep 'output.frequency:' | cut -d ' ' -f 2) <<< """$DATA""")
IN_VOLTAGE=$((grep 'input.voltage:' | cut -d ' ' -f 2) <<< """$DATA""")
IN_FREQ=$((grep 'input.frequency:' | cut -d ' ' -f 2) <<< """$DATA""")
BATTERY=$((grep 'battery.charge:' | cut -d ' ' -f 2) <<< """$DATA""")
LOAD=$((grep 'ups.load:' | cut -d ' ' -f 2) <<< """$DATA""")
fi
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range all ranges are inclusive
# of endpoints so we use less than or equal on the inside and just less
# than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# Check critical threshold
STATE=$STATE_OK
check_value "$VOLTAGE_CRITICAL" "$OUT_VOLTAGE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
check_value "$BATTERY_CRITICAL" "$BATTERY"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
check_value "$LOAD_CRITICAL" "$LOAD"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
# Check warning treshold
if [ $STATE -ne $STATE_CRITICAL ]; then
check_value "$VOLTAGE_WARNING" "$OUT_VOLTAGE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
check_value "$BATTERY_WARNING" "$BATTERY"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
check_value "$LOAD_WARNING" "$LOAD"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
fi
# Check ups state
if [ "$UPSSTATE" = "OL" ] ; then
UPSSTATE="ON-LINE"
elif [ "$UPSSTATE" = "OB" ] ; then
UPSSTATE="ON BATTERY"
STATE=$STATE_CRITICAL
else
STATE=$STATE_UNKNOWN
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="state: $UPSSTATE, output voltage: $OUT_VOLTAGE volt, battery: $BATTERY%, load: $LOAD% | voltage=$OUT_VOLTAGE freq=$OUT_FREQ in-voltage=$IN_VOLTAGE in-freq=$IN_FREQ battery=$BATTERY% load=$LOAD%"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_proc_ikus 0000775 0000000 0000000 00000027250 13431537440 0025240 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
# Nagios Process monitoring plugin.
#
# This plugin check the CPU and memory usage of a process.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-05-25
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="PROC"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s \
-p pidfile
[-c ] [-C ] \
[-m ] [-M ] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-c, --warning-cpu=val Set the warning cpu usage threshold (in %).
-C, --critical-cpu=val Set the critical cpu usage threshold (in %).
-m, --warning-mem=val Set the warning memmory usage threshold (in MB).
-M, --critical-mem=val Set the critical memory usage threshold (in MB).
-p, --pidfile=file Set the pidfile to monitor.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-t:,-c:,-C:,-m:,-M:,-f:,-F:,-p:" \
--longoptions "help,version,verbose,verbosity:,warning-cpu:,critical-cpu:,warning-memory:,critical-memory:,warning-fileopen:,critical-fileopen:,timeout:,pidfile:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-c | --warning-cpu)
shift
CPU_WARNING=$1;;
-C | --critical-cpu)
shift
CPU_CRITICAL=$1;;
-m | --warning-memory)
shift
MEM_WARNING=$1;;
-M | --critical-memory)
shift
MEM_CRITICAL=$1;;
-p | --pidfile)
shift
PIDFILE=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
function check_range {
# # positive values only
if [ ! -z "$1" ] ; then
WARNFORMAT=`echo "$1" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $WARNFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
if [ ! -z "$2" ] ; then
CRITFORMAT=`echo "$2" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $CRITFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
}
check_range "$CPU_WARNING" "$CPU_CRITICAL"
check_range "$MEM_WARNING" "$MEM_CRITICAL"
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Get PID to monitor.
PID=""
if [ -e "$PIDFILE" ]; then
PID=$(cat "$PIDFILE")
fi
# If process doesn't exists return Unknown.
if [ ! -e "/proc/$PID" ]; then
echo "UNKNOWN - process not running"
cleanup $STATE_UNKNOWN
fi
# Get the sensor's value
DATA=$(ps -p "$PID" efho vsize,rss,size,%cpu,nlwp)
if [ $VERBOSITY -gt 2 ] ; then
echo "$DATA"
fi
VSIZE_KB=$(echo "$DATA" | awk '{print $1;}')
VSIZE_MB=$(expr $VSIZE_KB / 1024)
RSS_KB=$(echo "$DATA" | awk '{print $2;}')
RSS_MB=$(expr $RSS_KB / 1024)
CPU=$(echo "$DATA" | awk '{print $4;}')
THREAD=$(echo "$DATA" | awk '{print $5;}')
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range all ranges are inclusive
# of endpoints so we use less than or equal on the inside and just less
# than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ $(echo "$START <= $2 && $2 <= $END" | bc) -eq 1 ] ; then
return 1
fi
else
if [ $(echo "$2 < $START || $END < $2" | bc) -eq 1 ] ; then
return 1
fi
fi
return 0
}
# Check critical threshold
STATE=$STATE_OK
check_value "$CPU_CRITICAL" "$CPU"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
check_value "$MEM_CRITICAL" "$RSS_MB"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
# Check warning treshold
if [ $STATE -ne $STATE_CRITICAL ]; then
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
check_value "$MEM_WARNING" "$RSS_MB"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="vsize: ${VSIZE_MB} MiB, rss: ${RSS_MB} MiB, cpu: $CPU%, threads: $THREAD | vsize=${VSIZE_KB}KiB rss=${RSS_KB}KiB cpu=${CPU}% threads=$THREAD"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_pwrstat_ikus 0000775 0000000 0000000 00000033533 13431537440 0026002 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
#
# This plugin check the state of a Cyber Power UPS using the utility tool
# named pwrstat This utility is provided directly from CyberPower. To work
# properly, this script required a sudo rules:
#
# nagios ALL=(ALL) NOPASSWD: /usr/sbin/pwrstat -status
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2012 Patrik Dufresne
# Create 2012-09-15
# Last modified 2015-08-21
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# you probably want to uncomment the following lines while developing
#shopt -o -s xtrace
# if you turn this on, then you have to alter the check_value calls to be able to check $?
#shopt -o -s errexit
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="PWRSTAT"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
PWRSTAT=/usr/sbin/pwrstat
if [ ! -x "$PWRSTAT" ] ; then
echo "pwrstat is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s \
[-wv ] [-cv ] \
[-wb ] [-cb ] \
[-wr ] [-cr ] \
[-wl ] [-cl ] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
--o, --warning-voltage=val Set the warning output voltage threshold.
--O, --critical-voltage=val Set the critical output voltage threshold.
--b, --warning-battery=val Set the warning percentage battery capacity threshold.
--B, --critical-battery=val Set the critical percentage battery capacity threshold.
--r, --warning-runtime=val Set the warning remaining runtime threshold.
--R, --critical-runtime=val Set the critical remaining runtime threshold.
--l, --warning-load=val Set the warning load percentage threshold.
--L, --critical-load=val Set the critical load percentage threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
#if [ $# -eq 0 ] ; then
# usage
#fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-t:,-o:,-O:,-b:,-B:,-r:,-R:,-l:,-L:" \
--longoptions "help,version,verbose,verbosity:,warning-voltage:,warning-battery:,warning-runtime:,warning-load:,critical-voltage:,critical-battery:,critical-runtime:,critical-load:,timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-o | --warning-voltage)
shift
VOLTAGE_WARNING=$1;;
-b | --warning-battery)
shift
BATTERY_WARNING=$1;;
-r | --warning-runtime)
shift
RUNTIME_WARNING=$1;;
-l | --warning-load)
shift
LOAD_WARNING=$1;;
-O | --critical-voltage)
shift
VOLTAGE_CRITICAL=$1;;
-B | --critical-battery)
shift
BATTERY_CRITICAL=$1;;
-R | --critical-runtime)
shift
RUNTIME_CRITICAL=$1;;
-L | --critical-load)
shift
LOAD_CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
function check_range {
# # positive values only
if [ ! -z "$1" ] ; then
WARNFORMAT=`echo "$1" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $WARNFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
if [ ! -z "$2" ] ; then
CRITFORMAT=`echo "$2" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $CRITFORMAT -lt 1 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
}
check_range "$VOLTAGE_WARNING" "$VOLTAGE_CRITICAL"
check_range "$BATTERY_WARNING" "$BATTERY_CRITICAL"
check_range "$RUNTIME_WARNING" "$RUNTIME_CRITICAL"
check_range "$LOAD_WARNING" "$LOAD_CRITICAL"
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Get the sensor's value
DATA=`sudo pwrstat -status`
if [ $VERBOSITY -gt 2 ] ; then
echo "$DATA"
fi
UPSSTATE=`echo "$DATA" | grep State |sed 's/.*State[ \.]\{1,\}\(.*\)/\1/'`
if [ "$UPSSTATE" != "Lost Communication" ]; then
VOLTAGE=`echo "$DATA" | grep 'Output Voltage' | grep -oe '[0-9]*'`
BATTERY=`echo "$DATA" | grep 'Battery Capacity' | grep -oe '[0-9]*'`
RUNTIME=`echo "$DATA" | grep 'Remaining Runtime' | grep -oe '[0-9]*'`
LOAD=`echo "$DATA" | grep Load | grep -oe '[0-9]* %' | grep -oe '[0-9]*'`
fi
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range all ranges are inclusive
# of endpoints so we use less than or equal on the inside and just less
# than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# Check UPS state
if [ "$UPSSTATE" = "Lost Communication" ]; then
OUT="Can't get UPS status: $UPSSTATE"
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT"
cleanup $STATE_UNKNOWN
fi
# Check critical threshold
STATE=$STATE_OK
check_value "$VOLTAGE_CRITICAL" "$VOLTAGE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
check_value "$BATTERY_CRITICAL" "$BATTERY"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
check_value "$RUNTIME_CRITICAL" "$RUNTIME"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
check_value "$LOAD_CRITICAL" "$LOAD"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
fi
# Check warning treshold
if [ $STATE -ne $STATE_CRITICAL ]; then
check_value "$VOLTAGE_WARNING" "$VOLTAGE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
check_value "$BATTERY_WARNING" "$BATTERY"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
check_value "$RUNTIME_WARNING" "$RUNTIME"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
check_value "$LOAD_WARNING" "$LOAD"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
fi
fi
# Check ups state
if [ "$UPSSTATE" = "Power Failure" ] ; then
STATE=$STATE_CRITICAL
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="state: $UPSSTATE, output voltage: $VOLTAGE volt, battery: $BATTERY%, remaining runtime: $RUNTIME min, load: $LOAD% | voltage=$VOLTAGE batery=$BATTERY% runtime=$RUNTIME load=$LOAD%"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_ro_mounts 0000775 0000000 0000000 00000007455 13431537440 0025274 0 ustar 00root root 0000000 0000000 #!/usr/bin/perl -w
# check_ro_mounts.pl Copyright (c) 2008 Valentin Vidic
#
# Checks the mount table for read-only mounts - these are usually a sign of
# trouble (broken filesystem etc.)
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# you should have received a copy of the GNU General Public License
# along with this program (or with Nagios); if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA
use strict;
use Getopt::Long;
use lib "/usr/local/nagios/libexec";
use lib $ENV{"HOME"} . "/bin";
use utils qw (%ERRORS &support);
my $name = 'RO_MOUNTS';
my $mtab = '/proc/mounts';
my @includes = ();
my @excludes = ();
my @excluded_types = ();
my @ro_mounts = ();
my $want_help = 0;
Getopt::Long::Configure(qw(no_ignore_case));
my $res = GetOptions(
"help|h" => \$want_help,
"mtab|m=s" => \$mtab,
"path|p=s" => \@includes,
"partition=s" => \@includes,
"exclude|x=s" => \@excludes,
"exclude-type|X=s" => \@excluded_types,
);
if ($want_help or !$res) {
print_help();
exit $ERRORS{$res ? 'OK' : 'UNKNOWN'};
}
my $includes_re = globs2re(@includes);
my $excludes_re = globs2re(@excludes);
my $excluded_types_re = globs2re(@excluded_types);
open(MTAB, $mtab) or nagios_exit(UNKNOWN => "Can't open $mtab: $!");
MOUNT: while () {
# parse mtab lines
my ($dev, $dir, $fs, $opt) = split;
my @opts = split(',', $opt);
# check includes/excludes
if ($includes_re) {
next MOUNT unless $dev =~ qr/$includes_re/
or $dir =~ qr/$includes_re/;
}
if ($excludes_re) {
next MOUNT if $dev =~ qr/$excludes_re/
or $dir =~ qr/$excludes_re/;
}
if ($excluded_types_re) {
next MOUNT if $fs =~ qr/$excluded_types_re/;
}
# check for ro option
if (grep /^ro$/, @opts) {
push @ro_mounts, $dir;
}
}
nagios_exit(UNKNOWN => "Read failed on $mtab: $!") if $!;
close(MTAB) or nagios_exit(UNKNOWN => "Can't close $mtab: $!");
# report findings
if (@ro_mounts) {
nagios_exit(CRITICAL => "Found ro mounts: @ro_mounts");
} else {
nagios_exit(OK => "No ro mounts found");
}
# convert glob patterns to a RE (undef if no patterns)
sub globs2re {
my(@patterns) = @_;
@patterns or return undef;
foreach (@patterns) {
s/ \\(.) / sprintf('\x%02X', ord($1)) /egx;
s/ ([^\\*?\w]) / sprintf('\x%02X', ord($1)) /egx;
s/\*/.*/g;
s/\?/./g;
}
return '\A(?:' . join('|', @patterns) . ')\z';
}
# output the result and exit plugin style
sub nagios_exit {
my ($result, $msg) = @_;
print "$name $result: $msg\n";
exit $ERRORS{$result};
}
sub print_help {
print <
This plugin checks the mount table for read-only mounts.
Usage:
check_ro_mounts [-m mtab] [-p path] [-x path] [-X type]
Options:
-h, --help
Print detailed help screen
-m, --mtab=FILE
Use this mtab instead (default is /proc/mounts)
-p, --path=PATH, --partition=PARTITION
Glob pattern of path or partition to check (may be repeated)
-x, --exclude=PATH
Glob pattern of path or partition to ignore (only works if -p unspecified)
-X, --exclude-type=TYPE
Ignore all filesystems of indicated type (may be repeated)
EOH
support();
}
# vim:sw=4:ts=4:et
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_sensors_ikus 0000775 0000000 0000000 00000041536 13431537440 0025774 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
# Check hardware sensor using `ipmitool` or `freeipmi`.
#
# Required the following sudoers
#
# nagios ALL=(ALL) NOPASSWD: /usr/bin/ipmitool sensor
# OR
# nagios ALL=(ALL) NOPASSWD: /usr/sbin/ipmi-sensors
# nagios ALL=(ALL) NOPASSWD: /usr/sbin/ipmi-dcmi
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-02-22
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# you probably want to uncomment the following lines while developing
#shopt -o -s xtrace
# if you turn this on, then you have to alter the check_value calls to be able to check $?
#shopt -o -s errexit
# You should provide a meaningful VERSION
VERSION=0.1
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="SENSOR"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
IPMITOOL=/usr/bin/ipmitool
FREEIPMI=/usr/sbin/ipmi-sensors
SENSORS=/usr/bin/sensors
if [ ! -x "$IPMITOOL" -a ! -x "$FREEIPMI" -a ! -x "$SENSORS" ] ; then
echo "neither $IPMITOOL, $FREEIPMI or $SENSORS is installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide detailed explanations of the command line syntax
function longhelp {
printf " %s %s for Nagios - Usage %s [-s \
-w -c ] \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-s, --sensor Set the sensor to monitor
-w, --warning=val Set the warning percentage threshold.
-c, --critical=val Set the critical percentage threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:,-s:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:,sensor:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare -i IDX=0
declare -a WARNING
declare -a CRITICAL
declare -a SENSOR
declare -a SENSOR_NAME
declare -a SENSOR_VALUE
declare -a SENSOR_UNIT
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING[IDX-1]=$1;;
-c | --critical)
shift
CRITICAL[IDX-1]=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-s | --sensor)
shift
SENSOR[IDX]=$1
IDX=$(( $IDX + 1 ))
;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# Check that the thresholds provided are valid strings
for W in ${WARNING[@]}; do
if [ ! -z "$W" ]; then
FORMAT=`echo "$W" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $FORMAT -lt 1 ] ; then
echo "Please check the format of your warning thresholds: $W"
range_help
fi
fi
done
for C in ${CRITICAL[@]}; do
if [ ! -z "$C" ]; then
FORMAT=`echo "$C" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
if [ $FORMAT -lt 1 ] ; then
echo "Please check the format of your critical thresholds: $C"
range_help
fi
fi
done
function normalize_unit {
if [ "$1" == "degreesC" ]; then
echo "C"
elif [ "$1" == "Volts" ]; then
echo "V"
elif [ "$1" == "discrete" ]; then
echo ""
elif [ "$1" == "discrete" ]; then
echo ""
elif [ "$1" == "Watts" ]; then
echo "watts"
else
echo "$1"
fi
}
function ipmi_enabled {
[ -e /dev/ipmi0 -o -e /dev/ipmi/0 -o -e /dev/ipmidev/0 ]
}
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# If IPMITOOL is available, use it.
if ipmi_enabled && [ -x "$IPMITOOL" ]; then
# Parse raw data
# FAN 1 | 1510.000 | RPM | ok | 400.000 | 585.000 | 770.000 | 29260.000 | 29815.000 | 30370.000
DATA=$(sudo -n "$IPMITOOL" sensor)
if [ $? -gt 0 ]; then
printf "UNKNOWN - Fail to execute $IPMITOOL. Check if sudo rule exists.\n"
cleanup $STATE_UNKNOWN
fi
# Capture data for each line.
IDX=0
while read LINE; do
SENSOR_NAME[$IDX]=$(echo $LINE | cut -d '|' -f 1 | sed -e 's/[ \t]*//g')
SENSOR_VALUE[$IDX]=$(echo $LINE | cut -d '|' -f 2 | sed -e 's/[ \t]*//g')
SENSOR_UNIT[$IDX]=$(echo $LINE | cut -d '|' -f 3 | sed -e 's/[ \t]*//g')
SENSOR_UNIT[$IDX]=$(normalize_unit "${SENSOR_UNIT[$IDX]}")
IDX=$(( $IDX + 1 ))
done <<< "$DATA"
elif ipmi_enabled && [ -x "$FREEIPMI" ]; then
# Parse raw data
# ID | Name | Reading | Units | Event
# 4 | CPU Temp | 25.00 | C | 'OK'
DATA=$(sudo -n "$FREEIPMI" --no-header-output --no-sensor-type-output --ignore-not-available-sensors)
if [ $? -gt 0 ]; then
printf "UNKNOWN - Fail to execute $FREEIPMI. Check if sudo rule exists.\n"
cleanup $STATE_UNKNOWN
fi
# Capture data for each line.
IDX=0
while read LINE; do
SENSOR_NAME[$IDX]=$(echo "$LINE" | cut -d '|' -f 2 | sed -e 's/[ \t]*//g')
SENSOR_VALUE[$IDX]=$(echo "$LINE" | cut -d '|' -f 3 | sed -e 's/[ \t]*//g')
SENSOR_UNIT[$IDX]=$(echo "$LINE" | cut -d '|' -f 4 | sed -e 's/[ \t]*//g')
SENSOR_UNIT[$IDX]=$(normalize_unit "${SENSOR_UNIT[$IDX]}")
IDX=$(( $IDX + 1 ))
done <<< "$DATA"
# Try to capture power stats
# Current Power : 62 Watts
DATA=$(sudo /usr/sbin/ipmi-dcmi --get-system-power-statistics | grep 'Power' | egrep -o "^[^:]*:\s*[+\-]?[0-9,\.]+\s?[^ ]*")
if [ $? -eq 0 ]; then
while read LINE; do
SENSOR_NAME[$IDX]=$(echo $LINE | cut -d ':' -f 1 | cut -d ' ' -f 1-2 | sed -e 's/[ \t]*//g')
SENSOR_VALUE[$IDX]=$(echo $LINE | cut -d ':' -f 2 | sed -e 's/[ \t]*//g' -e 's/[^0-9,\.\-]//g')
SENSOR_UNIT[$IDX]=$(echo $LINE | cut -d ':' -f 2 | sed -e 's/[ \t]*//g' -e 's/[0-9,\.\-+°]*//g')
SENSOR_UNIT[$IDX]=$(normalize_unit "${SENSOR_UNIT[$IDX]}")
IDX=$(( $IDX + 1 ))
done <<< "$DATA"
fi
elif [ -x "$SENSORS" ]; then
# Parse raw data
# Vcore: +0.78 V
DATA=$("$SENSORS" | egrep -o "^[^:]*:\s*[+\-]?[0-9,\.]+\s?[^ ]*")
if [ $? -gt 0 ]; then
printf "UNKNOWN - Fail to execute $SENSORS.\n"
cleanup $STATE_UNKNOWN
fi
# Capture data for each line.
IDX=0
while read LINE; do
SENSOR_NAME[$IDX]=$(echo $LINE | cut -d ':' -f 1 | sed -e 's/[ \t]*//g')
SENSOR_VALUE[$IDX]=$(echo $LINE | cut -d ':' -f 2 | sed -e 's/[ \t]*//g' -e 's/[^0-9,\.\-]//g')
SENSOR_UNIT[$IDX]=$(echo $LINE | cut -d ':' -f 2 | sed -e 's/[ \t]*//g' -e 's/[0-9,\.\-+°]*//g')
SENSOR_UNIT[$IDX]=$(normalize_unit "${SENSOR_UNIT[$IDX]}")
IDX=$(( $IDX + 1 ))
done <<< "$DATA"
fi
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
if [ -z "$1" ]; then
return 0
fi
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ $(echo "$START <= $2 && $2 <= $END" | bc) -eq 1 ] ; then
return 1
fi
elif [ $(echo "$2 < $START || $END < $2" | bc) -eq 1 ] ; then
return 1
fi
return 0
}
# check conditions - yes this is ugly, blame BASH.
# If you want to blame me, please provide a cleaner way that is as fast or faster
IDX=0
DESC=""
STATE=$STATE_OK
while [ "x${SENSOR[IDX]}" != "x" ]; do
IDX2=0
VALUE=""
while [ "x${SENSOR_NAME[IDX2]}" != "x" -a "${SENSOR_NAME[IDX2]}" != "${SENSOR[IDX]}" ]; do
IDX2=$(( $IDX2 + 1 ))
done
if [ "${SENSOR_NAME[IDX2]}" != "${SENSOR[IDX]}" ]; then
printf "UNKNOWN - Given sensors ${SENSOR[IDX]} doesn't exists.\n"
cleanup $STATE_UNKNOWN
fi
VALUE="${SENSOR_VALUE[IDX2]}"
check_value "${CRITICAL[IDX]}" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
if [ ! -z "$PERF" ]; then DESC="$DESC, "; fi
DESC="$DESC${SENSOR_NAME[IDX2]}: ${SENSOR_VALUE[IDX2]}${SENSOR_UNIT[IDX2]}"
fi
if [ ! $STATE -eq $STATE_CRITICAL ]; then
check_value "${WARNING[IDX]}" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
if [ ! -z "$PERF" ]; then DESC="$DESC, "; fi
DESC="$DESC${SENSOR_NAME[IDX2]}: ${SENSOR_VALUE[IDX2]}${SENSOR_UNIT[IDX2]}"
fi
fi
IDX=$(( $IDX + 1 ))
done
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
PERF=""
IDX=0
while [ "x${SENSOR_NAME[IDX]}" != "x" ]; do
# Skip N/A values.
if [ "${SENSOR_VALUE[IDX]}" != "N/A" -a "${SENSOR_VALUE[IDX]}" != "na" ]; then
if [ ! -z "$PERF" ]; then
PERF="$PERF "
fi
PERF="$PERF${SENSOR_NAME[IDX]}=${SENSOR_VALUE[IDX]}${SENSOR_UNIT[IDX]}"
fi
IDX=$(( $IDX + 1 ))
done
OUT="$SENSOR $VALUE $VALUE_UNIT | $SENSOR=${VALUE};$WARNING;$CRITICAL"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$DESC | $PERF";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$DESC | $PERF";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$DESC | $PERF";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$DESC | $PERF";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_smart_ikus 0000775 0000000 0000000 00000035436 13431537440 0025430 0 ustar 00root root 0000000 0000000 #!/bin/bash
###
#
# Check harddisk temperature using smartctl utility. This plugins reuiqred the
# following sudoers rule:
# nagios ALL=(ALL) NOPASSWD: /usr/sbin/smartctl *
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-04-10
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# you probably want to uncomment the following lines while developing
#shopt -o -s xtrace
# if you turn this on, then you have to alter the check_value calls to be able to check $?
#shopt -o -s errexit
# You should provide a meaningful VERSION
VERSION=0.2
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="SMART"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
SMARTCTL=/usr/sbin/smartctl
if [ ! -x "$SMARTCTL" ] ; then
echo "$SMARTCTL utility is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s -s \
-w -c \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-d, --device Set the device to monitor (may be define multiple time)
-w, --warning=val Set the temperature warning threshold.
-c, --critical=val Set the temperature critical threshold.
-t, --timeout=sec Set script timeout in seconds.
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
--range_help Explain threshold ranges.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-t:,-d:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,timeout:,device:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare WARNING
declare CRITICAL
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=15
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-d | --device)
shift
DEVICES="$DEVICES $1";;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 3 ] ; then
shopt -o -s xtrace
fi
# Check that the thresholds provided are valid strings
if [ -z "$WARNING" -o -z "$CRITICAL" ] ; then
range_help
else
# positive values only
WARNFORMAT=`echo "$WARNING" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
CRITFORMAT=`echo "$CRITICAL" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
OK=$(( $WARNFORMAT + $CRITFORMAT ))
if [ $OK -lt 2 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Check if a devices is provided
if [ -z "$DEVICES" ] ; then
# Scan for device list
SMARTCTL_DATA="$(sudo smartctl --scan)"
DEVICES=$(echo "$SMARTCTL_DATA" | cut -d ' ' -f 1 2>/dev/null)
if [[ $(echo "$SMARTCTL_DATA" | grep -c 'UNRECOGNIZED OPTION') -gt 0 ]]; then
# --scan option was not supported, use shell globbing
DEVICES="$(ls /dev/sd?)"
fi
fi
# Make sure we found devices.
if [ -z "$DEVICES" ] ; then
usage
fi
# Loop on each devices
# Build some kind of data array to latter parsing.
COUNT=-1
DATA=()
for DEVICE in $DEVICES; do
# Check if device exists
if [ ! -b "$DEVICE" ]; then
echo "UNKNOWN - The device '$DEVICE' is invalid."
cleanup $STATE_UNKNOWN
fi
# Get SMART data
LINES=`sudo -n $SMARTCTL -a $DEVICE`
if [[ -z "$LINES" ]]; then
#Given device doesn't exists
printf "UNKNOWN - Given device '$DEVICE' doesn't exists.\n"
cleanup $STATE_UNKNOWN
fi
# Check if device support SMART
ENABLED=$(echo "$LINES" | grep -c 'SMART support is: Enabled')
# Parse the data.
if [ $ENABLED -gt 0 ]; then
HEALTH=`echo $(echo "$LINES" | grep "SMART overall-health" | head -n 1 | cut -d ':' -f 2 )`
TEMPERATURE=$(echo "$LINES" | grep "Temperature_Celsius" | head -n 1 | awk '{print $10;}')
[ -z "$TEMPERATURE" ] && TEMPERATURE="0"
ID_005=$(echo "$LINES" | grep "Reallocated_Sector_Ct" | head -n 1 | awk '{print $10;}')
[ -z "$ID_005" ] && ID_005="0"
ID_196=$(echo "$LINES" | grep "Reallocated_Event_Count" | head -n 1 | awk '{print $10;}')
[ -z "$ID_196" ] && ID_196="0"
ID_198=$(echo "$LINES" | grep "Offline_Uncorrectable" | head -n 1 | awk '{print $10;}')
[ -z "$ID_198" ] && ID_198="0"
ID_199=$(echo "$LINES" | grep "UDMA_CRC_Error_Count" | head -n 1 | awk '{print $10;}')
[ -z "$ID_199" ] && ID_199="0"
DATA+=("$DEVICE $HEALTH $TEMPERATURE $ID_005 $ID_196 $ID_198 $ID_199")
let "COUNT += 1"
fi
done
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
function check_value {
# If the range starts with an @, alert if value is inside the range,
# otherwise alert if value is outside of range.
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# Start is anything left of the colon or 0.
# End is anything right of the colon or the whole string if there's no
# colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# CHECK DATA
STATE=$STATE_OK
OUT=""
PERF="|"
for i in `seq 0 $COUNT`; do
LINE=$(echo "${DATA[$i]}")
if [ $VERBOSITY -gt 2 ] ; then
echo $LINE
fi
DEVICE=$(echo "$LINE" | awk '{print $1;}')
DEVICE=$(basename "$DEVICE")
HEALTH=$(echo "$LINE" | awk '{print $2;}')
TEMPERATURE=$(echo "$LINE" | awk '{print $3;}')
ID_005=$(echo "$LINE" | awk '{print $4;}')
ID_196=$(echo "$LINE" | awk '{print $5;}')
ID_198=$(echo "$LINE" | awk '{print $6;}')
ID_199=$(echo "$LINE" | awk '{print $7;}')
# Append performance data
PERF+=" ${DEVICE}_temp=$TEMPERATURE ${DEVICE}_reallocated_sector_count=$ID_005 ${DEVICE}_reallocated_event_count=$ID_196 ${DEVICE}_offline_uncorrectable=$ID_198 ${DEVICE}_udma_crc_error_count=$ID_199"
OUT+="$DEVICE"
# Check critical thresholds
if [ "$HEALTH" != "PASSED" ]; then
STATE=$STATE_CRITICAL
OUT+=" $HEALTH"
fi
# Check sectors
if [ "$ID_005" -gt 5 -o "$ID_196" -gt 5 -o "$ID_198" -gt 5 -o "$ID_199" -gt 5 ]; then
STATE=$STATE_CRITICAL
OUT+=" bad sectors"
fi
# Check temperature
if [ ! -z "$CRITICAL" ]; then
check_value "$CRITICAL" "$TEMPERATURE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
OUT+=" critical temperature"
fi
fi
# Check warning thresholds
if [ ! -z "$WARNING" -a $STATE != $STATE_CRITICAL ]; then
check_value "$WARNING" "$TEMPERATURE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
OUT+=" warning temperature"
fi
fi
if [ ! -z "$OUT" -a $i -lt $COUNT ]; then
OUT+=", "
fi
done
case $STATE in
$STATE_OK)
printf "%s OK: %s\n" "$SERVICE" "$OUT $PERF";;
$STATE_WARNING)
printf "%s WARNING: %s\n" "$SERVICE" "$OUT $PERF";;
$STATE_CRITICAL)
printf "%s CRITICAL: %s\n" "$SERVICE" "$OUT $PERF";;
$STATE_UNKNOWN)
printf "%s UNKNOWN: %s\n" "$SERVICE" "$OUT $PERF";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_snmp_memutil_ikus 0000775 0000000 0000000 00000021271 13431537440 0027003 0 ustar 00root root 0000000 0000000 #!/usr/bin/perl
#
#
# AUTHORS:
# Copyright (C) 2003-2012 Opsview Limited. All rights reserved
#
# This file is part of Opsview
#
# Opsview is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Opsview is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Opsview; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# MODIFIED:
# July 25, 2012 by Patrik Dufresne. Take the buffered and chaced value in
# consideration
use lib qw ( /usr/local/nagios/perl/lib );
use Net::SNMP;
use Getopt::Std;
use warnings;
use strict;
my $script = 'check_snmp_memutil';
my $script_version = '3.0';
my $metric = 1;
my $oid_sysDescr = ".1.3.6.1.2.1.1.1.0";
my $memTotalSwap = ".1.3.6.1.4.1.2021.4.3.0";
my $memTotalReal = ".1.3.6.1.4.1.2021.4.5.0";
my $memAvailSwap = ".1.3.6.1.4.1.2021.4.4.0";
my $memAvailReal = ".1.3.6.1.4.1.2021.4.6.0";
my $memCached = ".1.3.6.1.4.1.2021.4.15.0";
my $memBuffered = ".1.3.6.1.4.1.2021.4.14.0";
my $version = "1";
my $timeout = 2;
my $real_warning = 90;
my $real_critical = 95;
my $swap_warning = 90;
my $swap_critical = 95;
my $status = 0;
my $returnstring = "";
my $port = 161;
my $hostname;
my $community = "public"; # Default community string
# SNMP values
my $availreal = 0;
my $availswap = 0;
my $totalmemused = 0;
my $totalreal = 0;
my $totalrealmb = 0;
my $totalswap = 0;
my $totalswapmb = 0;
my $usedreal = 0;
my $usedrealmb = 0;
my $usedrealpercentage = 0;
my $usedswap = 0;
my $usedswapmb = 0;
my $usedswappercentage = 0;
my $buffered = 0;
my $bufferedmb = 0;
my $cached = 0;
my $cachedmb = 0;
# Do we have enough information?
if ( @ARGV < 1 ) {
print "Too few arguments$/";
usage();
}
our ( $opt_h, $opt_H, $opt_C, $opt_w, $opt_c, $opt_x, $opt_d, $opt_p, $opt_v );
getopts("hH:C:w:c:x:d:p:v:");
if ($opt_h) {
usage();
exit(0);
}
if ($opt_H) {
$hostname = $opt_H;
}
else {
print "No hostname specified$/";
usage();
}
if ($opt_C) {
$community = $opt_C;
}
if ($opt_w) {
$real_warning = $opt_w;
$real_warning =~ s/%//g;
}
if ($opt_c) {
$real_critical = $opt_c;
$real_critical =~ s/%//g;
}
if ($opt_x) {
$swap_warning = $opt_x;
$swap_warning =~ s/%//g;
}
if ($opt_d) {
$swap_critical = $opt_d;
$swap_critical =~ s/%//g;
}
if ($opt_p) {
$port = $opt_p;
}
if ($opt_v) {
if ( $opt_v ne "1" && $opt_v ne "2c" ) {
print "SNMP version must be 1 or 2c (not $opt_v)$/";
usage();
}
else {
$version = $opt_v;
}
}
# Create the SNMP session
my ( $s, $e ) = Net::SNMP->session(
-community => $community,
-hostname => $hostname,
-version => $version,
-timeout => $timeout,
-port => $port,
);
main();
# Close the session
$s->close();
if ( $returnstring eq "" ) {
$status = 3;
}
if ( $status == 0 ) {
print "OK - $returnstring$/";
}
elsif ( $status == 1 ) {
print "WARNING - $returnstring$/";
}
elsif ( $status == 2 ) {
print "CRITICAL - $returnstring$/";
}
else {
print "UNKNOWN - Plugin error?$/";
}
exit $status;
sub main {
# Swap
if ( !defined( $s->get_request($memTotalSwap) ) ) {
if ( !defined( $s->get_request($oid_sysDescr) ) ) {
$returnstring = "SNMP agent not responding";
$status = 1;
return 1;
}
else {
$returnstring = "SNMP OID does not exist";
$status = 1;
return 1;
}
}
foreach ( $s->var_bind_names() ) {
$totalswap = $s->var_bind_list()->{$_};
}
if ( !defined( $s->get_request($memAvailSwap) ) ) {
if ( !defined( $s->get_request($oid_sysDescr) ) ) {
$returnstring = "SNMP agent not responding";
$status = 1;
return 1;
}
else {
$returnstring = "SNMP OID does not exist";
$status = 1;
return 1;
}
}
foreach ( $s->var_bind_names() ) {
$availswap = $s->var_bind_list()->{$_};
}
$usedswap = $totalswap - $availswap;
if( $totalswap > 0 ) {
$usedswappercentage = ( 100 / $totalswap ) * $usedswap;
}
$usedswapmb = $usedswap / 1024;
# printf "Swap memory used: %.0f percent (%.0f Mb)$/", $usedswappercentage, $usedswapmb ;
# Real
if ( !defined( $s->get_request($memTotalReal) ) ) {
if ( !defined( $s->get_request($oid_sysDescr) ) ) {
$returnstring = "SNMP agent not responding";
$status = 1;
return 1;
}
else {
$returnstring = "SNMP OID does not exist";
$status = 1;
return 1;
}
}
foreach ( $s->var_bind_names() ) {
$totalreal = $s->var_bind_list()->{$_};
# $totalreal = sprintf("%.2f",$totalreal);
}
if ( !defined( $s->get_request($memAvailReal) ) ) {
if ( !defined( $s->get_request($oid_sysDescr) ) ) {
$returnstring = "SNMP agent not responding";
$status = 1;
return 1;
}
else {
$returnstring = "SNMP OID does not exist";
$status = 1;
return 1;
}
}
foreach ( $s->var_bind_names() ) {
$availreal = $s->var_bind_list()->{$_};
# $availreal = sprintf("%.2f",$availreal);
}
# Buffered
if ( !defined( $s->get_request($memBuffered) ) ) {
if ( !defined( $s->get_request($oid_sysDescr) ) ) {
$returnstring = "SNMP agent not responding";
$status = 1;
return 1;
}
else {
$returnstring = "SNMP OID does not exist";
$status = 1;
return 1;
}
}
foreach ( $s->var_bind_names() ) {
$buffered = $s->var_bind_list()->{$_};
# $availreal = sprintf("%.2f",$availreal);
}
# Cached
if ( !defined( $s->get_request($memCached) ) ) {
if ( !defined( $s->get_request($oid_sysDescr) ) ) {
$returnstring = "SNMP agent not responding";
$status = 1;
return 1;
}
else {
$returnstring = "SNMP OID does not exist";
$status = 1;
return 1;
}
}
foreach ( $s->var_bind_names() ) {
$cached = $s->var_bind_list()->{$_};
# $availreal = sprintf("%.2f",$availreal);
}
$totalrealmb = $totalreal / 1024;
$totalswapmb = $totalswap / 1024;
$usedreal = $totalreal - ( $cached + $buffered + $availreal);
$usedrealpercentage = ( 100 / $totalreal ) * $usedreal;
$usedrealmb = $usedreal / 1024;
$cachedmb = $cached / 1024;
$bufferedmb = $buffered / 1024;
$totalmemused = $usedrealpercentage + $usedswappercentage;
$returnstring .= sprintf "USAGE: real %.0f%% (%.0f/%.0fMB), buffer: %.0fMB, cache: %.0fMB, swap %.0f%% (%.0f/%.0f MB)|", $usedrealpercentage, $usedrealmb, $totalrealmb, $bufferedmb, $cachedmb, $usedswappercentage, $usedswapmb, $totalswapmb;
# Perf data
$returnstring .= sprintf "used_real_pct=%.0f%% used_real_mb=%.0f used_swap_pct=%.0f%% used_swap_mb=%.0f cached_mb=%.0f buffered_mb=%.0f", $usedrealpercentage, $usedrealmb, $usedswappercentage, $usedswapmb, $cachedmb, $bufferedmb;
if ( $usedrealpercentage >= $real_critical ) {
$status = 2;
}
elsif ( $usedswappercentage >= $swap_critical ) {
$status = 2;
}
elsif ( $usedrealpercentage >= $real_warning ) {
$status = 1;
}
elsif ( $usedswappercentage >= $swap_warning ) {
$status = 1;
}
else {
$status = 0;
}
}
sub usage {
print << "USAGE";
$script v$script_version
Returns memory utilisation stats for Linux / Unix systems
Usage: $script -H -C [...]
Options: -H Hostname or IP address
-p Port (default: 161)
-C Community (default is public)
-w Real memory warning threshold (as % used)
-c Real memory critical threshold (as % used)
-x Swap warning threshold (as % used)
-d Swap critical threshold (as % used)
USAGE
exit 3;
}
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_snmp_procs_ikus 0000775 0000000 0000000 00000024551 13431537440 0026461 0 ustar 00root root 0000000 0000000 #! /bin/bash
###
# Checks process using SNMP.
#
# @AUTHOR: Patrik Dufresne
# Copyright 2012 Patrik Dufresne
# Last modified 2012-12-22
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=0.2
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="PROCS"
BASE_HR_SWRUNNAME_OID=".1.3.6.1.2.1.25.4.2.1.2"
# replacement for the exit function, will cleanup any tempfiles or such before exiting
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# since we couldn't define STATE_UNKNOWN since reading utils.sh failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and executable. The following example is stupid because of course date is installed but it's the only command this trivial check really uses
SNMPWALK=`which snmpwalk`
if [ ! -x "$SNMPWALK" ] ; then
echo "Snmpwalk is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf "%s %s for Nagios - Usage %s -H -n [-w ] [-c ] [-C ] [-p ] [-t ] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-w, --warning=range Set the warning threshold (default: 0:).
-c, --critical=range Set the critical threshold (default: 0:).
-H, --host=hostname Set the hostname or IP address.
-C, --community=community Set the community string (default: public).
-p, --port= port Set the snmp port to use (default: 161) .
-n, --name=process Set the process name.
-t, --timeout=sec Set script timeout in seconds (default: 15).
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
# explanatory function you probably want to keep
function range_help {
printf "
The format for ranges in Nagios can be confusing and it isn't always followed.
[@]start[:[end]]
Here are some example ranges:
Range | Generate an alert if value is | In English
--------+-----------------------------------+---------------------------------
10 | outside the range of {0 .. 10} | Greater than 10
@10 | inside the range of {0 .. 10} | Less than or equal to 10
10: | outside {10 .. ∞} | Greater than 10
~:10 | outside the range of {-∞ .. 10} | Less than 10 including negative
10:20 | outside the range of {10 .. 20} | Between 10 and 20
@10:20 | inside the range of {10 .. 20} | Anything from 10 to 20
10 | outside the range of {0 .. 10} | Greater than 10 or less than 0
Formal Rules:
1. start ≤ end
2. start and ":" is not required if start=0
3. if range is of format \"start:\" and end is not specified, end is infinity
4. to specify negative infinity, use "~"
5. alert is raised if metric is outside start and end range (inclusive)
6. if range starts with "@", then alert if inside this range (inclusive)
10 < 0 or > 10, (outside the range of {0 .. 10})
10: < 10, (outside {10 .. ∞})
~:10 > 10, (outside the range of {-∞ .. 10})
10:20 < 10 or > 20, (outside the range of {10 .. 20})
@10:20 ≥ 10 and ≤ 20, (inside the range of {10 .. 20})
10 < 0 or > 10, (outside the range of {0 .. 10})
More help at http://nagiosplug.sourceforge.net/developer-guidelines.html
"
cleanup $STATE_UNKNOWN
}
if [ $# -eq 0 ] ; then
usage
fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# tell it which switches and longswitches you'll take and place a trailing colon (:) on the ones take arguments
# Nagios guidelines require you to use all the ones specified below with the exception of --verbosity which I've added to circumvent the awkward -v -v -v syntax
# getopt takes care of positional parameters and errors for missing expected arguments so we can shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-c:,-w:,-H:-C:,-p:,-n:,-t:" --longoptions "help,version,verbose,verbosity:,warning:,critical:,host:,community:,port:,name,timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
WARNING="0:"
CRITICAL="0:"
declare -i TIMELIMIT=15
declare -i VERBOSITY=0
COMMUNITYSTRING=public
declare -i PORT=161
declare PROCESS
declare HOST
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity) # THIS IS NOT IN THE DEVELOPER GUIDELINES BUT FEELS MORE NATURAL THAN -v -v -v
shift
VERBOSITY=$1;;
-w | --warning)
shift
WARNING=$1;;
-c | --critical)
shift
CRITICAL=$1;;
-H | --host)
shift
HOST=$1;;
-C | --community)
shift
COMMUNITYSTRING=$1;;
-p | --port)
shift
PORT=$1;;
-n | --name)
shift
PROCESS=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# Check argument values
if [ -z "$WARNING" -o -z "$CRITICAL" ] ; then
echo "Please provide warning and critical threshold."
usage
else
# positive values only
WARNFORMAT=`echo "$WARNING" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
CRITFORMAT=`echo "$CRITICAL" | grep -c '^@\?\([0-9]\+:[0-9]*\|[0-9]\+\)$'`
OK=$(( $WARNFORMAT + $CRITFORMAT ))
if [ $OK -lt 2 ] ; then
echo "Please check the format of your warning and critical thresholds."
range_help
fi
fi
if [ -z "$HOST" ]; then
echo "Please provide hostname."
usage
fi
if [ -z "$PROCESS" ]; then
echo "Please provide process name."
usage
fi
# what needs to happen in the event of a timeout
function timeout {
echo "$SERVICE UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit, we can setup a timeout trap now
trap timeout USR1
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
DATA=`snmpwalk -v 2c -c "$COMMUNITYSTRING" "$HOST:$PORT" "$BASE_HR_SWRUNNAME_OID" 2>&1`
RETURN=$?
if [ $RETURN -gt 0 ]; then
printf "%s UNKNOWN - %s\n" "$SERVICE" "$DATA"
cleanup $STATE_UNKNOWN
fi
VALUE=`echo "$DATA" | grep -c "STRING: \"${PROCESS}\""`
# once we're done doing work that could take any real time, we can end the trap because from here on out it's just comparisons and string concatenation
trap - USR1
function check_value {
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
INSIDE=`echo "$1" | grep -c '^@'`
RANGE=`echo "$1" | sed 's/^@//'`
# start is anything left of the colon or 0
# end is anything right of the colon or the whole string if there's no colon or infinity if there is a colon and nothing to the right of it
# is there a colon?
PARTS=`echo "$RANGE" | awk -F : '{ print NF }'`
if [ $PARTS -gt 1 ] ; then
START=${RANGE%%:*}
END=${RANGE##*:}
else
START=0
END=$RANGE
fi
# 4. to specify negative infinity, use "~"
if [ "$START" == "~" ] ; then
START=-999999999
fi
if [ -z "$END" ] ; then
END=999999999
fi
if [ $START -gt $END ] ; then
echo "In threshold START:END, START must be less than or equal to END"
range_help
fi
# if the range starts with an @, alert if value is inside the range, otherwise alert if value is outside of range
# all ranges are inclusive of endpoints so we use less than or equal on the inside and just less than on the outside
if [ "$INSIDE" -gt 0 ] ; then
if [ "$START" -le "$2" -a "$2" -le "$END" ] ; then
return 1
fi
else
if [ "$2" -lt "$START" -o "$END" -lt "$2" ] ; then
return 1
fi
fi
return 0
}
# check conditions - yes this is ugly, blame BASH. If you want to blame me, please provide a cleaner way that is as fast or faster
check_value "$CRITICAL" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_CRITICAL
else
check_value "$WARNING" "$VALUE"
if [ $? -gt 0 ] ; then
STATE=$STATE_WARNING
else
STATE=$STATE_OK
fi
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="$VALUE processes with command name '$PROCESS' | procs=${VALUE};$WARNING;$CRITICAL"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_ssllabs_ikus 0000775 0000000 0000000 00000020326 13431537440 0025735 0 ustar 00root root 0000000 0000000 #! /bin/bash
#
# Check SSL security using sslab.
#
# @AUTHOR: Patrik Dufresne (http://patrikdufresne.com)
# Copyright 2015 Patrik Dufresne
# Last modified 2015-03-21
# Please send all comments, suggestions, bugs and patches to (info AT patrikdufresne DOT com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
###
# You should provide a meaningful VERSION
VERSION=1.0
# Who can be contacted about this?
AUTHOR="Patrik Dufresne"
# Name what is being checked to be printed out next to OK/WARNING/CRITICAL/UNKNOWN
SERVICE="SSL LABS"
# Define the ssllab url
SSLLABAPIURI="https://api.ssllabs.com/api/v2"
# Replacement for the exit function, will cleanup any tempfiles or such
# before exiting.
function cleanup {
exit $1
}
declare -rx PROGNAME=${0##*/}
declare -rx PROGPATH=${0%/*}/
if [ -r "${PROGPATH}utils.sh" ] ; then
source "${PROGPATH}utils.sh"
else
echo "Can't find utils.sh. This plugin needs to be run from the same directory as utils.sh which is most likely something like /usr/lib/nagios/plugins or /usr/lib64/nagios/plugins"
printf "Currently being run from %s\n" "$PROGPATH"
# Since we couldn't define STATE_UNKNOWN since reading utils.sh
# failed, we use 3 here but everywhere else after this use cleanup $STATE
cleanup 3
fi
# Set STATE to UNKNOWN as soon as we can (right after reading in util.sh
# where the STATES are defined)
STATE=$STATE_UNKNOWN
# make sure that any external commands are installed, in the PATH and
# executable. The following example is stupid because of course date is
# installed but it's the only command this trivial check really uses
CURL=/usr/bin/curl
if [ ! -x "$CURL" ] ; then
echo "The utility is not installed, in your path and executable. Exiting."
cleanup $STATE_UNKNOWN
fi
# provide a quick one liner of how to use the program
function usage {
printf " %s %s for Nagios - Usage %s -H \
[-t timeout] [-v [-v [-v]]]\n" "$PROGNAME" "$VERSION" "$PROGNAME"
cleanup $STATE_UNKNOWN
}
# provide detailed explanations of the command line syntax
function longhelp {
# put your long help here
printf "%s plugin version %s for Nagios by %s
-h, --help Display this message.
-H, --hostname The hostname to lookup SSL.
-t, --timeout=sec Set script timeout in seconds (default 60sec).
-v, --verbose Up the verbosity level by one.
--verbosity=val Set the verbosity level to val.
-V, --version Print version information.
" "$PROGNAME" "$VERSION" "$AUTHOR"
cleanup $STATE_UNKNOWN
}
if [ $# -eq 0 ] ; then
usage
fi
# use getopt, trust me on this one. It's the easiest way
getopt -T
if [ $? -ne 4 ] ; then
printf "%s: getopt is in compatibility mode.\n" "$SCRIPT"
cleanup $STATE_UNKNOWN
fi
# Tell it which switches and longswitches you'll take and place a trailing
# colon (:) on the ones take arguments. Nagios guidelines require you to
# use all the ones specified below with the exception of --verbosity which I've
# added to circumvent the awkward -v -v -v syntax. Getopt takes care of
# positional parameters and errors for missing expected arguments so we can
# shift later without checking
RESULT=`getopt --name "$SCRIPT" --options "-h,-V,-v,-H:,-t:" --longoptions "help,version,verbose,verbosity:,hostname:timeout:" -- "$@"`
# make the result of getopt your new argument list ($@)
eval set -- "$RESULT"
declare HOSTNAME
# all scripts should have a mechanism to terminate themselves if they are
# running for too long. Scripts you might think of as innocuous could end
# up waiting forever on I/O, especially if a disk is failing
declare -i TIMELIMIT=60
# Nagios defines behavior for VERBOSITY 0 (default) through 3
declare -i VERBOSITY=0
while [ $# -gt 0 ] ; do
case "$1" in
-h | --help)
longhelp;;
-V | --version)
print_revision "$PROGNAME" "$VERSION"
cleanup $STATE;;
-v | --verbose)
VERBOSITY=$(($VERBOSITY + 1));;
--verbosity)
shift
VERBOSITY=$1;;
-t | --timeout)
shift
TIMELIMIT=$1;;
-H | --hostname)
shift
HOSTNAME=$1;;
--)
shift
break;;
*)
echo "Option $1 not supported. Ignored." >&2;;
esac
shift
done
#Verbosity level Type of output
#0 Single line, minimal output. Summary
#1 Single line, additional information (eg list processes that fail)
#2 Multi line, configuration debug output (eg ps command used)
#3 Lots of detail for plugin problem diagnosis
if [ $VERBOSITY -gt 2 ] ; then
shopt -o -s xtrace
fi
# what needs to happen in the event of a timeout
function timeout {
echo "UNKNOWN - script timed out after $TIMELIMIT seconds."
cleanup $STATE_UNKNOWN
}
# since we've processed the options which potentially set the timeout limit,
# we can setup a timeout trap now
trap timeout USR1
# what we're doing here sending a USR1 signal back to this process which
# we just set a trap to catch and run the timeout function the syntax of
# this is important and very odd - if you know of a better way to do this,
# please email me what we're doing is starting another process in the
# background that sleeps for TIMELIMIT seconds and then uses pgrep when
# it 'wakes up' to see if a process with our number, name and user exists,
# only then will the USR1 signal be sent we have to use pgrep so that we
# don't sent a USR1 signal to just any program. The only risk we run with
# this is sending USR1 to another instance of this script that just happens
# to get assigned the same process ID it should be reasonable to assume
# that your Nagios check interval is greater than the specified timeout
# still, if you havea better idea...
( sleep $TIMELIMIT; if [ `pgrep -U $USER -f "$SCRIPT" | grep -c ^$$$` -gt 0 ] ; then kill -USR1 $$ ; fi; ) /dev/null &
# Check that hostname is provided
if [ -z "$HOSTNAME" ] ; then
usage
fi
# Get the score
STATUS=""
while [ "$STATUS" != "READY" ]; do
DATA=$($CURL -k -s "${SSLLABAPIURI}/analyze?host=$HOSTNAME&all=done&fromCache=on")
if [[ -z "$DATA" ]]; then
# Can't get data !
printf "UNKNOWN - Fail to get ssl info.\n"
cleanup $STATE_UNKNOWN
fi
# Get the reference status
STATUS=$((sed ':a;N;$!ba;s/\n//g' | grep -o '"status":\s*"[A-Z]*"' | cut -d ':' -f 2 | sed 's/"//g' | sed 's/ //g') <<< """$DATA""" )
if [ "$STATUS" != "READY" ]; then
if [ $VERBOSITY -gt 1 ] ; then
echo "Status not ready. Waiting 10 secs..."
echo "$STATUS"
fi
# sleep 10 secs
sleep 10
fi
done
GRADE=$((sed ':a;N;$!ba;s/\n//g' | egrep -o '"grade":\s*"[A-Z][+\-]?"' | cut -d ':' -f 2 | sed 's/"//g' | sed 's/ //g') <<< """$DATA""" )
MSG=$((sed ':a;N;$!ba;s/\n//g' | egrep -o '"statusMessage":\s*"[a-zA-Z0-9 .]*"' | cut -d ':' -f 2 | sed 's/"//g' ) <<< """$DATA""" )
# Once we're done doing work that could take any real time, we can end the
# trap because from here on out it's just comparisons and string
# concatenation
trap - USR1
# check conditions - yes this is ugly, blame BASH. If you want to blame me, please provide a cleaner way that is as fast or faster
if [ "$GRADE" == "A+" -o "$GRADE" == "A" -o "$GRADE" == "A-" ]; then
STATE=$STATE_OK
elif [ "$GRADE" == "B+" -o "$GRADE" == "B" -o "$GRADE" == "B-" ]; then
STATE=$STATE_WARNING
elif [ "$GRADE" == "C+" -o "$GRADE" == "C" -o "$GRADE" == "C-" ]; then
STATE=$STATE_WARNING
else
STATE=$STATE_CRITICAL
fi
# STATE - Message | 'label'=value[unit of measure];[warn];[crit];[min];[max]
OUT="$HOSTNAME $MSG, grade: $GRADE"
case $STATE in
$STATE_OK)
printf "%s OK - %s\n" "$SERVICE" "$OUT";;
$STATE_WARNING)
printf "%s WARNING - %s\n" "$SERVICE" "$OUT";;
$STATE_CRITICAL)
printf "%s CRITICAL - %s\n" "$SERVICE" "$OUT";;
$STATE_UNKNOWN)
printf "%s UNKNOWN - %s\n" "$SERVICE" "$OUT";;
esac
cleanup $STATE
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_syncrepl 0000775 0000000 0000000 00000023466 13431537440 0025106 0 ustar 00root root 0000000 0000000 #!/usr/bin/python
import os
import sys
import getpass
import ldap
import time
import datetime
import re
import logging
from optparse import OptionParser
LdapDelta= "";
__doc__ = """
This script checks if a consumer is in synch with its provider based on
the contextCSN. The check can be performed for several consumers.
If a threshold is specified, the consumer and its provider is considered
in synch if the difference in contextCSN value is less than the threshold
value.
Version 1.1 with OpenLDAP 2.4 support
"""
def getUserPassword():
"""
Get user password
This function returns the password (string)
"""
# get password input
password = getpass.getpass('Password: ')
return password
def create_logger(application, verbose=None, logfile=None):
"""
Create logger instance to log to console and/or to file
application - program's name (string)
verbose - verbose logging (boolean)
logfile - log file name (string)
This function returns a logger instance
"""
if verbose:
lowestseverity = logging.DEBUG
else:
lowestseverity = logging.INFO
# Create logger
logger = logging.getLogger(application)
logger.setLevel(lowestseverity)
# Create console handler and set level to lowestseverity
ch = logging.StreamHandler()
ch.setLevel(lowestseverity)
# Create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# Add formatter to console handler
ch.setFormatter(formatter)
# Add console handler to logger
logger.addHandler(ch)
if logfile:
# Create file handler and set level to debug
fh = logging.FileHandler(logfile)
fh.setLevel(lowestseverity)
# Add formatter to console handler and file handler
fh.setFormatter(formatter)
# Add file handler to logger
logger.addHandler(fh)
return logger
def ldap_connect(ldapuri, logger=None, binddn="", bindpw=""):
"""
Perform LDAP connection and synchronous simple bind operation
ldapuri - URI referring to the LDAP server (string)
binddn - Distinguished Name used to bind (string)
logger - Logger object instance
This function returns an LDAPobject instance if successful,
None if failure
"""
# Set debugging level
ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0)
ldap_trace_level = 0 # If non-zero a trace output of LDAP calls is generated.
ldap_trace_file = sys.stderr
# Create LDAPObject instance
if logger: logger.debug("Connecting to %s" % ldapuri)
conn = ldap.initialize(ldapuri,
trace_level=ldap_trace_level,
trace_file=ldap_trace_file)
# Set LDAP protocol version used
if logger: logger.debug("LDAP protocol version 3")
conn.protocol_version=ldap.VERSION3
# Perform synchronous simple bind operation
if binddn:
password = bindpw
if logger: logger.debug("Binding with %s" % binddn)
else:
if logger: logger.debug("Binding anonymously")
password = "";
try:
conn.bind_s(binddn, password, ldap.AUTH_SIMPLE)
return conn
except ldap.LDAPError, error_message:
if logger: logger.error("LDAP bind failed. %s" % error_message)
print("FAILED : LDAP bind failed. %s" % error_message)
return None
def ldap_search(ldapobj, basedn, scope, filter, attrlist):
"""
Perform LDAP synchronous search operation
ldapobj - LDAP object instance
basedn - LDAP base dn (string)
scope - LDAP search scope (integer)
filter - LDAP filter (string)
attrlist - LDAP attributes (list)
This function returns a result set (list),
None if no attribute was found
"""
result_set = (ldapobj.search_s(basedn, scope, filter, attrlist))
return result_set
def get_contextCSN(ldapobj, basedn, logger=None):
"""
Retrieve contextCSN attribute value for the suffix dn
ldapobj - LDAP object instance
basedn - LDAP base dn (string)
This function returns the contextCSN value (string),
None if no value was found
"""
result_list = ldap_search(ldapobj, basedn, ldap.SCOPE_BASE, '(objectclass=*)', ['contextCSN'])
if result_list[0][1].has_key('contextCSN'):
if logger: logger.debug("contextCSN = %s" % result_list[0][1]['contextCSN'][0] )
return result_list[0][1]['contextCSN'][0]
else:
if logger: logger.error("No contextCSN was found")
return None
def contextCSN_to_datetime(contextCSN):
"""
Convert contextCSN string (YYYYmmddHHMMMSSZ#...) to datetime object
contextCSN - Timestamp in YYYYmmddHHMMSSZ#... format (string)
This function returns a datetime object instance
"""
gentime = re.sub('(\.\d{6})?Z.*$','',contextCSN)
return datetime.datetime.fromtimestamp(time.mktime(time.strptime(gentime,"%Y%m%d%H%M%S")))
def threshold_to_datetime(threshold):
"""
Convert threshold in seconds to datetime object
threshold - seconds (integer)
This function returns a datetime object instance
"""
nbdays, nbseconds = divmod(threshold, 86400)
return datetime.timedelta(days=nbdays, seconds=nbseconds)
def is_insynch(provldapobj, consldapobj, basedn, threshold=None, logger=None):
"""
Check if the consumer is in synch with the provider within the threshold
provldapobj - Provider LDAP object instance
consldapobj - Consumer LDAP object instance
basedn - LDAP base dn (string)
threshold - limit above which provider and consumer are not considered
in synch (int)
This function returns False if the provider and the consumer is not
in synch, True if in synch within the threshold
"""
if logger: logger.debug("Retrieving Provider contextCSN")
provcontextCSN = get_contextCSN(provldapobj, basedn, logger)
if logger: logger.debug("Retrieving Consumer contextCSN")
conscontextCSN = get_contextCSN(consldapobj, basedn, logger)
if (provcontextCSN and conscontextCSN):
if (provcontextCSN == conscontextCSN):
if logger: logger.info(" Provider and consumer exactly in SYNCH")
print("OK - Provider and consumer exactly in SYNCH")
return True
else:
delta = contextCSN_to_datetime(provcontextCSN) - contextCSN_to_datetime(conscontextCSN)
LdapDelta= "Delta is: %s" % delta;
if threshold:
maxdelta = threshold_to_datetime(eval(threshold))
if logger: logger.debug("Threshold is %s" % maxdelta)
if (abs(delta) <= maxdelta):
if logger:
logger.info(" Consumer in SYNCH within threshold")
logger.info(" Delta is %s" % delta)
print("OK - Delta is %s|%s" % (delta, delta))
return True
else:
if logger: logger.info(" Consumer NOT in SYNCH within threshold")
else:
if logger: logger.info(" Consumer NOT in SYNCH")
if logger: logger.info(" Delta is %s" % delta)
print ("FAILED - Delta is %s|%s" % (delta, delta))
else:
if logger: logger.error(" Check failed: at least one contextCSN value is missing")
print("Check failed: at least one contextCSN value is missing")
return False
def main():
IsInSync= True;
usage = "\n " + sys.argv[0] + """ [options] providerLDAPURI consumerLDAPURI ...
This script takes at least two arguments:
- providerLDAPURI is the provider LDAP URI (as defined in RFC2255)
- consumerLDAPURI is the consumer LDAP URI (as defined in RFC2255)
Additional consumer LDAP URIs can be specified.
"""
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
default=False,
help="""Enable more verbose output""")
parser.add_option("-q", "--quiet", dest="quiet", action="store_true",
default=False,
help="""Disable console and file logging""")
parser.add_option("-n", "--nagios", dest="nagios", action="store_true",
default=False,
help="""Enable for Nagios""")
parser.add_option("-p", "--password", dest="password",
default="",
help="""Bind password""")
parser.add_option("-P", "--Password2", dest="password2",
default="",
help="""Bind password2 for consumers""")
parser.add_option("-l", "--logfile", dest="logfile", default=re.sub("\.[^\.]*$","",sys.argv[0]) + '.log',
help="""Log the actions of this script to this file
[ default : %default ]""")
parser.add_option("-D", "--binddn",
dest="binddn", default="",
help="""Use the Distinguished Name to bind [default:
anonymous]. You will be prompted to enter the
associated password.""")
parser.add_option("-b", "--basedn",
dest="basedn", default="dc=amnh,dc=org",
help="LDAP base dn [default: %default].")
parser.add_option("-t", "--threshold", dest="threshold",
default=None,
help="""Threshold value in seconds""")
(options, args) = parser.parse_args()
if not options.quiet:
# Create the logger object to log to console and/or file
logger = create_logger(os.path.basename(sys.argv[0]), options.verbose, options.logfile)
else:
logger = None
if logger: logger.info("Provider is: %s" % re.sub("^.*\/\/", "", args[0]))
ldapprov = ldap_connect(args.pop(0), logger, options.binddn, options.password)
if ldapprov:
for consumer in args:
if logger: logger.info("Checking if consumer %s is in SYNCH with provider" % re.sub("^.*\/\/", "", consumer))
ldapcons = ldap_connect(consumer, logger, options.binddn, options.password2)
if ldapcons:
IsInSync = IsInSync and is_insynch(ldapprov, ldapcons, options.basedn, options.threshold, logger)
ldapcons.unbind_s()
else:
sys.exit(1)
ldapprov.unbind_s()
if (options.nagios):
if (IsInSync):
sys.exit(0)
else:
sys.exit(2)
else:
sys.exit(1)
if __name__ == '__main__':
main()
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/check_zpools 0000775 0000000 0000000 00000012431 13431537440 0024563 0 ustar 00root root 0000000 0000000 #!/usr/bin/env bash
#########################################################################
# Script: check_zpools.sh
# Purpose: Nagios plugin to monitor status of zfs pool
# Authors: Aldo Fabi First version (2006-09-01)
# Vitaliy Gladkevitch Forked (2013-02-04)
# Claudio Kuenzler Complete redo, perfdata, etc (2013-2014)
# Doc: http://www.claudiokuenzler.com/nagios-plugins/check_zpools.php
# History:
# 2006-09-01 Original first version
# 2006-10-04 Updated (no change history known)
# 2013-02-04 Forked and released
# 2013-05-08 Make plugin work on different OS, pepp up plugin
# 2013-05-09 Bugfix in exit code handling
# 2013-05-10 Removed old exit vars (not used anymore)
# 2013-05-21 Added performance data (percentage used)
# 2013-07-11 Bugfix in zpool health check
# 2014-02-10 Bugfix in threshold comparison
# 2014-03-11 Allow plugin to run without enforced thresholds
#########################################################################
### Begin vars
STATE_OK=0 # define the exit code if status is OK
STATE_WARNING=1 # define the exit code if status is Warning
STATE_CRITICAL=2 # define the exit code if status is Critical
STATE_UNKNOWN=3 # define the exit code if status is Unknown
# Set path
PATH=$PATH:/usr/sbin:/sbin
export PATH
### End vars
#########################################################################
help="check_zpools.sh (c) 2006-2014 several authors\n
Usage: $0 -p (poolname|ALL) [-w warnpercent] [-c critpercent]\n
Example: $0 -p ALL -w 80 -c 90"
#########################################################################
# Check necessary commands are available
for cmd in zpool awk [
do
if ! `which ${cmd} 1>/dev/null`
then
echo "UNKNOWN: ${cmd} does not exist, please check if command exists and PATH is correct"
exit ${STATE_UNKNOWN}
fi
done
#########################################################################
# Check for people who need help - aren't we all nice ;-)
if [ "${1}" = "--help" -o "${#}" = "0" ];
then
echo -e "${help}";
exit ${STATE_UNKNOWN};
fi
#########################################################################
# Get user-given variables
while getopts "p:w:c:" Input;
do
case ${Input} in
p) pool=${OPTARG};;
w) warn=${OPTARG};;
c) crit=${OPTARG};;
*) echo -e $help
exit $STATE_UNKNOWN
;;
esac
done
#########################################################################
# Did user obey to usage?
if [ -z $pool ]; then echo -e $help; exit ${STATE_UNKNOWN}; fi
#########################################################################
# Verify threshold sense
if [[ -n $warn ]] && [[ -z $crit ]]; then echo "Both warning and critical thresholds must be set"; exit $STATE_UNKNOWN; fi
if [[ -z $warn ]] && [[ -n $crit ]]; then echo "Both warning and critical thresholds must be set"; exit $STATE_UNKNOWN; fi
if [[ $warn -gt $crit ]]; then echo "Warning threshold cannot be greater than critical"; exit $STATE_UNKNOWN; fi
#########################################################################
# What needs to be checked?
## Check all pools
if [ $pool = "ALL" ]
then
POOLS=($(sudo -S zpool list -Ho name))
p=0
for POOL in ${POOLS[*]}
do
CAPACITY=$(sudo -S zpool list -Ho capacity $POOL | awk -F"%" '{print $1}')
HEALTH=$(sudo -S zpool list -Ho health $POOL)
# Check with thresholds
if [[ -n $warn ]] && [[ -n $crit ]]
then
if [[ $CAPACITY -ge $crit ]]
then error[${p}]="POOL $POOL usage is CRITICAL (${CAPACITY}%)"; fcrit=1
elif [[ $CAPACITY -ge $warn && $CAPACITY -lt $crit ]]
then error[$p]="POOL $POOL usage is WARNING (${CAPACITY}%)"
elif [ $HEALTH != "ONLINE" ]
then error[${p}]="$POOL health is $HEALTH"; fcrit=1
fi
# Check without thresholds
else
if [ $HEALTH != "ONLINE" ]
then error[${p}]="$POOL health is $HEALTH"; fcrit=1
fi
fi
perfdata[$p]="$POOL=${CAPACITY}% "
let p++
done
if [[ ${#error[*]} -gt 0 ]]
then
if [[ $fcrit -eq 1 ]]; then exit_code=2; else exit_code=1; fi
echo "ZFS POOL ALARM: ${error[*]}|${perfdata[*]}"; exit ${exit_code}
else echo "ALL ZFS POOLS OK (${POOLS[*]})|${perfdata[*]}"; exit 0
fi
## Check single pool
else
CAPACITY=$(sudo -S zpool list -Ho capacity $pool | awk -F"%" '{print $1}')
HEALTH=$(sudo -S zpool list -Ho health $pool)
if [[ -n $warn ]] && [[ -n $crit ]]
then
# Check with thresholds
if [ $HEALTH != "ONLINE" ]; then echo "ZFS POOL $pool health is $HEALTH|$pool=${CAPACITY}%"; exit ${STATE_CRITICAL}
elif [[ $CAPACITY -gt $crit ]]; then echo "ZFS POOL $pool usage is CRITICAL (${CAPACITY}%|$pool=${CAPACITY}%)"; exit ${STATE_CRITICAL}
elif [[ $CAPACITY -gt $warn && $CAPACITY -lt $crit ]]; then echo "ZFS POOL $pool usage is WARNING (${CAPACITY}%)|$pool=${CAPACITY}%"; exit ${STATE_WARNING}
else echo "ALL ZFS POOLS OK ($pool)|$pool=${CAPACITY}%"; exit ${STATE_OK}
fi
else
# Check without thresholds
if [ $HEALTH != "ONLINE" ]
then echo "ZFS POOL $pool health is $HEALTH|$pool=${CAPACITY}%"; exit ${STATE_CRITICAL}
else echo "ALL ZFS POOLS OK ($pool)|$pool=${CAPACITY}%"; exit ${STATE_OK}
fi
fi
fi
echo "UKNOWN - Should never reach this part"
exit ${STATE_UNKNOWN}
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/pnp4nagios/ 0000775 0000000 0000000 00000000000 13431537440 0024233 5 ustar 00root root 0000000 0000000 nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/pnp4nagios/check_cpu_ikus.php 0000664 0000000 0000000 00000005417 13431537440 0027732 0 ustar 00root root 0000000 0000000
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/pnp4nagios/check_drools.php 0000664 0000000 0000000 00000005417 13431537440 0027412 0 ustar 00root root 0000000 0000000
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/pnp4nagios/check_memory_ikus.php 0000664 0000000 0000000 00000005740 13431537440 0030452 0 ustar 00root root 0000000 0000000
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/pnp4nagios/check_sensors_ikus.php 0000664 0000000 0000000 00000016766 13431537440 0030650 0 ustar 00root root 0000000 0000000 .
# Array with different colors
$colors = array(
"fce94f",
"fcaf3e",
"8ae232",
"729fcf",
"ad7fa8",
"ef2920",
"c4a000",
"ce5c00",
"4e9a06",
"204a87",
"5c3566",
"a40000",
"edd400",
"f57900",
"73d216",
"3465a4",
"75507b",
"cc0000");
$colors = array("0022ff", "22ff22", "ff0000", "00aaaa", "ff00ff",
"ffa500", "cc0000", "0000cc", "0080C0", "8080C0",
"FF0080", "800080", "688e23", "408080", "808000",
"000000", "00FF00", "0080FF", "FF8000", "800000",
"FB31FB");
# Counters
$t = 0; # temp probe counter
$w = 0; # watt probe counter
$v = 0; # volt probe counter
$f = 0; # fan probe counter
$o = 0; # other probe counter
# Flags
$visited_amp = 0;
# IDs
$id_temp = 1;
$id_watt = 2;
$id_volt = 3;
$id_fan = 4;
$id_other = 5;
# Enclosure id
$enclosure_id = '';
# Default title
$def_title = 'Sensors';
# Temperature unit
if (!defined('tempunit_defined')) {
define('tempunit_defined', 1);
function tempunit($arg)
{
$unit = 'unknown';
$vlabel = 'unknown';
switch ($arg) {
default:
$vlabel = "Celsius";
$unit = "°C";
break;
case "F":
$vlabel = "Fahrenheit";
$unit = "°F";
break;
case "K":
$vlabel = "Kelvin";
$unit = "K";
break;
case "R":
$vlabel = "Rankine";
$unit = "°R";
break;
}
return array($unit, $vlabel);
}
}
#------------------------------------------------------
# MAIN LOOP
#------------------------------------------------------
# Loop through the performance data
foreach ($this->DS as $KEY=>$VAL) {
$label = $VAL['LABEL'];
# TEMPERATURES
if (preg_match('/^temp/', $label) ||
preg_match('/TIN$/', $label) ||
preg_match('/Temp$/', $label) ||
preg_match('/Physicalid\d/', $label) ||
preg_match('/Core\d/', $label) ||
$VAL['UNIT'] == "C") {
# Temperature unit and vertical label
list ($unit, $vlabel) = tempunit($VAL['UNIT']);
# Long label
$label = preg_replace('/^(.*)Temp$/', '$1', $label);
$label = preg_replace('/^(.*)TIN$/', '$1', $label);
$label = preg_replace('/_/', ' ', $label);
$ds_name[$id_temp] = "Temperatures";
$opt[$id_temp] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: Chassis Temperatures\" ";
if (isset($def[$id_temp])) {
$def[$id_temp] .= rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ;
}
else {
$def[$id_temp] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ;
}
$def[$id_temp] .= rrd::line1("var$KEY", "#".$colors[$t++], rrd::cut($label,20) );
$def[$id_temp] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%4.1lf $unit");
}
# WATTAGE PROBE
elseif (preg_match('/^W/', $label) || preg_match('/Power$/', $label)) {
# Long label
$label = preg_replace('/^(.+)Power$/', '$1', $label);
$ds_name[$id_watt] = "Power Consumption";
$vlabel = "Watts";
$title = $ds_name[$id_watt];
$opt[$id_watt] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" ";
if(isset($def[$id_watt])){
$def[$id_watt] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'],"AVERAGE");
}
else {
$def[$id_watt] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE");
}
$def[$id_watt] .= rrd::line1("var$KEY", "#".$colors[$w++], rrd::cut($label,18) ) ;
$def[$id_watt] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%8.2lf A");
}
# VOLTAGE PROBE
elseif ( preg_match('/^V/', $label) ||
preg_match('/^in\d$/', $label) ||
preg_match('/^AVCC$/', $label) ||
preg_match('/V$/', $label) ||
preg_match('/^3VSB$/', $label) ||
$VAL['UNIT'] == "V") {
# Long label
$label = preg_replace('/^V(\d+)_(.+)/', '$2', $label);
$label = preg_replace('/_/', ' ', $label);
# Short label
$label = preg_replace('/^V(\d+)$/', 'Probe $1', $label);
$ds_name[$id_volt] = "Voltage Probes";
$vlabel = "Volts";
$title = $ds_name[$id_volt];
$opt[$id_volt] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" ";
if(isset($def[$id_volt])){
$def[$id_volt] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'],"AVERAGE");
}
else {
$def[$id_volt] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE");
}
$def[$id_volt] .= rrd::line1("var$KEY", "#".$colors[$v++], rrd::cut($label,18) ) ;
$def[$id_volt] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%8.2lf V");
}
# FANS (RPMs)
elseif (preg_match('/^fan/i', $label) || $VAL['UNIT'] == "RPM") {
$ds_name[$id_fan] = "Fan Speeds";
$vlabel = "Volts";
$title = $ds_name[$id_fan];
$opt[$id_fan] = "-X0 --slope-mode --vertical-label \"RPMs\" --title \"$def_title: $title\" ";
if(isset($def[$id_fan])){
$def[$id_fan] .= rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'], "AVERAGE") ;
}
else {
$def[$id_fan] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'], "AVERAGE") ;
}
$def[$id_fan] .= rrd::line1("var$KEY", "#".$colors[$f++], rrd::cut($label,18) ) ;
$def[$id_fan] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf RPM");
}
# OTHERS
else {
if ($VAL['UNIT'] == "%%") {
$vlabel = "%";
$upper = " --upper=101 ";
$lower = " --lower=0 ";
}
else {
$vlabel = $VAL['UNIT'];
$upper = "";
$lower = "";
}
$opt[$id_other] = '--vertical-label "' . $vlabel . '" --title "' . $def_title . ': ' . $label . '"' . $upper . $lower;
$ds_name[$id_other] = $VAL['LABEL'];
$def[$id_other] = rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE");
#$def[$id_other] .= rrd::gradient("var$KEY", "3152A5", "BDC6DE", rrd::cut($VAL['NAME'],16), 20);
$def[$id_other] .= rrd::line1 ("var$KEY", "#".$colors[$o++], rrd::cut($label,18) );
$def[$id_other] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%3.4lf ".$VAL['UNIT']);
#$def[$id_other] .= rrd::comment("Default Template\\r");
#$def[$id_other] .= rrd::comment("Command " . $VAL['TEMPLATE'] . "\\r");
$id_other++;
}
}
?>
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/pnp4nagios/stat_net.php 0000664 0000000 0000000 00000005033 13431537440 0026566 0 ustar 00root root 0000000 0000000 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
#
# Changelog:
# v0.9 2010.10.22 (ts)
#
####
$base = 2; # Datasources per Group/Device
$smap = array (
'in' => array(
'type' => 'AREA',
'color' => '#00e060',
),
'out' => array(
'type' => 'LINE1',
'color' => '#0080e0',
),
);
$dev = array();
foreach ( $this->DS as $k=>$v ) {
$i = intval($k/$base) +1;
if ( $k%$base == 0 ) { # Some definitions at beginning
if ( preg_match( "/^(.*)_in$/",$v['NAME'], $treffer ) ) {
$dev[$i] = $treffer[1];
$ds_name[$i] = $dev[$i];
}
$opt[$i] = "--vertical-label Bytes/sec -lo --title '$hostname / $servicedesc - $ds_name[$i]' ";
#$this->MACRO['DISP_HOSTNAME']
#$this->MACRO['DISP_SERVICEDESC']
$def[$i] = "";
$UNIT[$i] = "B";
$UNIT[$i+1] = "B";
}
if ( preg_match( "/^$dev[$i]_(.*)$/",$v['NAME'], $treffer ) ) {
$v['sname'] = $treffer[1];
} else {
$v['sname'] = $v['NAME'];
}
$def[$i] .= rrd::def("v$k", $v['RRDFILE'], $v['DS'], "AVERAGE" );
#$def[$i] .= rrd::line(1,"v$k", $map_color[$k%$base], "$k\\n");
$def[$i] .= $smap[$v['sname']]['type'].":v$k".$smap[$v['sname']]['color'].":".
sprintf("'%-20s' ",$dev[$i]." ".$v['sname']);
$def[$i] .= rrd::gprint("v$k","LAST","%7.1lf %s$UNIT[$i]/s last");
$def[$i] .= rrd::gprint("v$k","AVERAGE","%7.1lf %s$UNIT[$i]/s avg");
$def[$i] .= rrd::gprint("v$k","MAX","%7.1lf %s$UNIT[$i]/s max");
#$def[$i] .= rrd::comment("\\n");
#if ( $k%$base == $base-1 ) { # Some definitions at the end
# $def[$i] .= rrd::hrule( 10*131072, "#333", "10MBit/s");
# $def[$i] .= rrd::hrule( 100*131072, "#773", "100MBit/s");
# $def[$i] .= rrd::hrule( 1024*131072, "#484", "1GBit/s");
# $def[$i] .= rrd::hrule(10240*131072, "#844", "10GBit/s");
# $def[$i] .= rrd::comment("\\n");
#}
}
?>
nagios-plugins-0a6a6e1b97b9abc5a6d0cbedc0e0e2c5ca92d1f5/stat_net 0000775 0000000 0000000 00000007050 13431537440 0023722 0 ustar 00root root 0000000 0000000 #!/usr/bin/perl -w
################################################
#
# Checks the net-stat (only for status).
# - warning state only for to much percent of errs or drop packages
# - unknown is for unknown device
#
# Thomas Sesselmann 2010
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
#
#
# Changelog:
# v0.9 2010.10.22 (ts)
#
####
my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);
my $warn = "10";
my $proc_net_file = "/proc/net/dev";
my %devices = ();
&get_params(@ARGV);
&test_net();
#####################################################
sub test_net() {
my $return_txt='';
my $perfdata='';
my $status = 'OK';
open FILE,"<$proc_net_file";
while() {
chomp $_;
if ($_ =~ /^\s*(\w+):(.*)$/){
my $key = lc $1;
if(( exists $devices{all} )or( exists $devices{$key} )) {
$devices{$key}=$2;
}
}
}
close FILE;
foreach my $k ( sort keys %devices ) {
if ( $k eq "all" ) { next; }
if ( $devices{$k} eq "0" ) {
$status = 'UNKNOWN';
if ( $return_txt ne "" ) { $return_txt .= ", " }
$return_txt .= "$k=(-/-)";
next;
}
my @val = split " ",$devices{$k};
my $rx = $val[0];
my $tx = $val[8];
$perfdata .= "${k}_in=${rx}c; "; #In Bytes (Counter)
$perfdata .= "${k}_out=${tx}c; "; #Out Bytes (Counter)
## calculate dops and errors to percent
if ( ( ($val[2]+$val[3]) * 100 > $warn * $rx ) or
( ($val[10]+$val[11]) * 100 > $warn * $tx ) ) {
if ( $ERRORS{$status} < $ERRORS{'WARNING'} ) { $status ='WARNING'; }
}
my $rx_unit = "B";
if ( $rx > 1024 * 4 ) { $rx /= 1024; $rx_unit="kB"; }
if ( $rx > 1024 * 4 ) { $rx /= 1024; $rx_unit="MB"; }
if ( $rx > 1024 * 4 ) { $rx /= 1024; $rx_unit="GB"; }
if ( $rx > 1024 * 4 ) { $rx /= 1024; $rx_unit="TB"; }
my $tx_unit = "B";
if ( $tx > 1024 * 4 ) { $tx /= 1024; $tx_unit="kB"; }
if ( $tx > 1024 * 4 ) { $tx /= 1024; $tx_unit="MB"; }
if ( $tx > 1024 * 4 ) { $tx /= 1024; $tx_unit="GB"; }
if ( $tx > 1024 * 4 ) { $tx /= 1024; $tx_unit="TB"; }
if ( $return_txt ne "" ) { $return_txt .= ", " }
$return_txt .= sprintf "$k=(%.1f$rx_unit/%.1f$tx_unit)",$rx,$tx;
}
$return_txt = "NET $status - (Rx/Tx) $return_txt|$perfdata\n";
&print_exit($return_txt,$ERRORS{$status});
}
sub get_params() {
# get params
my $test = '';
foreach $key (@_){
if($test eq '') { $test = $key; next; }
if($test eq '-w') { $warn = $key; $test = ''; next; }
if($test =~ /^-/) { &print_usage(); }
$devices{$key}=0;
}
if($test ne '') {
$devices{$test}=0;
}
if( keys %devices == 0 ) { $devices{all}=0; }
if( $warn =~ /^(\d+)%?$/ ) {
$warn = $1;
} else {
&print_usage;
}
}
sub print_usage() {
print "Usage: $0 [-w ] [devices]*\n";
exit $ERRORS{'UNKNOWN'};
}
sub print_exit() {
my $msg = shift;
my $return_code = shift;
print "$msg";
exit $return_code;
}
__END__