Skip to content

Instantly share code, notes, and snippets.

@jrohland
Created March 15, 2015 13:20
Show Gist options
  • Save jrohland/06665653057c8c402492 to your computer and use it in GitHub Desktop.
Save jrohland/06665653057c8c402492 to your computer and use it in GitHub Desktop.
Sensu plugin for checking number of connections to a port
#!/bin/bash
#
# Check netstat for number of connections to a specified port
#
# ===
#
# Examples:
#
# # check by port number
# connection-metrics.sh -p port
#
# Date: 2015-03-15
# Author: Jesse Rohland <jesse.rohland@gmail.com>
#
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
# get arguments
while getopts 'p:h' OPT; do
case $OPT in
p) PORT=$OPTARG;;
h) hlp="yes";;
*) unknown="yes";;
esac
done
# usage
HELP="
usage: $0 [ -p value -h ]
-p --> port
-h --> print this help screen
"
if [ "$hlp" = "yes" ]; then
echo "$HELP"
exit 0
fi
if [ ${PORT} ]; then
conns=`netstat -an | grep ${PORT}`
listen=`echo "$conns" | grep LISTEN | wc -l`
established=`echo "$conns" | grep ESTABLISHED | wc -l`
timeout=`echo "$conns" | grep TIME_WAIT | wc -l`
close=`echo "$conns" | grep CLOSE_WAIT | wc -l`
hostname=`hostname`
timestamp=`date +%s`
echo "${hostname}.conns_${PORT}.listen ${listen} ${timestamp}"
echo "${hostname}.conns_${PORT}.established ${established} ${timestamp}"
echo "${hostname}.conns_${PORT}.timeout ${timeout} ${timestamp}"
echo "${hostname}.conns_${PORT}.close ${close} ${timestamp}"
exit 0
fi
echo "$HELP"
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment