triggertrace/triggertrace
2021-11-16 14:15:54 +00:00

147 lines
3.1 KiB
Bash

#!/usr/bin/env bash
##################################
# Constants / global variables
##################################
SCRIPTNAME=`basename "$0"`
VERSION="0.0.1"
LOGLEVEL=INFO
LOGFILE=/var/log/triggertrace.log
INTERFACE=eth0 # interface to monitor
CAPDEST=/tmp/ # capture destination path
THRESHOLD=4000 # threshold in packets per second (pps)
SLEEPTIME=30 # sleeptime in seconds
HELP_TEXT="
$SCRIPTNAME v$VERSION
This is triggertrace, it will create tcpdump tracefiles
when a threshold of pps has been triggered
Usage:
$SCRIPTNAME -l <logfile> -L <loglevel> <command>
Options:
-h|--help Display this help
-l|--logfile Specify logfile with path (Default: /var/log/triggertrace.log)
-L|--loglevel Logging level needs to be DEBUG, INFO, WARN or ERROR. (Default: INFO)
Command:
start start triggertrace (Required)
Examples:
$SCRIPTNAME start
$SCRIPTNAME -l mylogfile.log -L INFO start
"
##################################
# Functions
##################################
# Logging functions
log_output () {
echo `date "+%Y/%m/%d %H:%M:%S"`" $1"
echo `date "+%Y/%m/%d %H:%M:%S"`" $1" >> $LOGFILE
}
log_debug () {
if [[ "$LOGLEVEL" =~ ^(DEBUG)$ ]]; then
log_output "DEBUG $1"
fi
}
log_info () {
if [[ "$LOGLEVEL" =~ ^(DEBUG|INFO)$ ]]; then
log_output "INFO $1"
fi
}
log_warn () {
if [[ "$LOGLEVEL" =~ ^(DEBUG|INFO|WARN)$ ]]; then
log_output "WARN $1"
fi
}
log_error () {
if [[ "$LOGLEVEL" =~ ^(DEBUG|INFO|WARN|ERROR)$ ]]; then
log_output "ERROR $1"
fi
}
# Help output
usage () {
echo "$HELP_TEXT"
}
main () {
log_output "starting $0"
while /bin/true; do
pktbefore=`grep $INTERFACE: /proc/net/dev | cut -d : -f2 | awk '{ print $2 }'`
sleep 1
pktafter=`grep $INTERFACE: /proc/net/dev | cut -d : -f2 | awk '{ print $2 }'`
pkts=$(( $pktafter - $pktbefore ))
log_output "`date` $pkts packets/s"
if [ $pkts -gt $THRESHOLD ]; then
log_output "`date` threshold over $THRESHOLD pps, capturing 2000 packets."
tcpdump -n -s0 -c 2000 -w $CAPDEST/trace-"$(date +"%Y_%m_%d_%H_%M")".cap
log_output "`date` Packets captured, sleeping $SLEEPTIME seconds..."
sleep $SLEEPTIME
fi
done
}
#################################
# Main
#################################
# Check if a param is set to a valid value
if [[ ! "$LOGLEVEL" =~ ^(DEBUG|INFO|WARN|ERROR)$ ]]; then
log_error "Logging level needs to be DEBUG, INFO, WARN or ERROR."
usage
exit 1
fi
# display usage when no parameter specified
if [[ ! "$1" ]]; then
usage
exit 0
fi
# Get input parameters
while [[ "$1" != "" ]]; do
case "$1" in
-l | --logfile )
shift
LOGFILE=$1
;;
-L | --loglevel )
shift
LOGLEVEL=$1
;;
-h | --help )
usage
exit 0
;;
-* )
echo -e "Error: Unknown parameter: $1\r" >&2
usage
exit 1
;;
start )
main "$@"
;;
* )
echo -e "Error: Unknown command: $1\r" >&2
usage
exit 1
;;
esac
shift
done
# logic starts here
main "$@"