#!/usr/local/bin/bash
#title :Process Sniffer
#description :The purpose of this script is to periodically grab aspecific process by name (if unique)
# or PID (if not unique). Useful for observing how the process is using resources over time.
#author :Joe
#date :20130221
#version :1.0
#usage :Executed via command-line like ./psniff.sh
#notes :Utilizes top, filters the output to what is specified and appends the current date and time
#bash_version :4.0.33(0)-release (you get this by running echo $BASH_VERSION from the prompt)
#bash_full :GNU bash, version 4.0.33(0)-release (amd64-portbld-freebsd8.0) (you get this by running bash --version from the prompt)
# Define a few global variables
showInteractive=1 # Useful if you are running this yourself. 0 = show no messages to screen, 1 = show messages to screen.
logProgress=1 # 0 = do not create/use log in /var/log, 1 = create/use log
wStill=5 # Number of seconds to wait before repeating
wRecur=1440 # Number of times to repeat (1440). In this case, with a 5 second wait, will run for 2 hours.
wtHead="USERNAME" # Pull the TOP process header. Since this varies by linux flavor and you may have a process running
# with the same text, you'll need to pick out something unique so that the TOP process header line is extracted.
wGrp="mysqld" # What process to pull out of top. Since this is in a GREP, only return lines with mysqld.
logFile="/var/log/psniff.log" # Location of the log file, if you want the output recorded to a log.
# Do not change
wCollection=""
wRecurCnt=0
wFinish=0
exCode=0
if [ $showInteractive == 1 ] || [ $logProgress == 1 ]; then
# Pull out the top process header line
wtTxt=`top | grep -E $wtHead`
set -- $wtTxt
# Start Recursion
while [ $wFinish == 0 ]
do
# Grab top output and append with the current date and time
cDate=`date +%m-%d-%Y_%H:%M:%S`
wtTxtLp=`top | grep -E $wGrp`
set -- $wtTxtLp
wCollection=$wtTxtLp" "$cDate
# Show to screen if set
if [ $showInteractive == 1 ]; then
# Show top header line
if [ $wRecurCnt == 0 ]; then
echo $wtTxt
fi
# Show the process line
echo $wCollection
fi
# Save output to file in /var/log if set
if [ $logProgress == 1 ]; then
if [ -f $logFile ]; then
# Append data to file
# Save header line
if [ $wRecurCnt == 0 ]; then
echo $wtTxt >> $logFile
fi
# Save content
echo $wCollection >> $logFile
else
# Create new file
touch $logFile
# Assign root as owner
chown root $logFile
# Assign 0644 permissions to the file
chmod u+rw,g+r,o+r $logFile
# Dump content into file
echo $wtTxt > $logFile
echo $wCollection >> $logFile
fi
fi
# Increment loop count and evaluate exit
wRecurCnt=$(( $wRecurCnt + 1 ))
if [ $wRecurCnt == $wRecur ]; then
wFinish=$(( 1 ))
fi
sleep $wStill
done
if [ $showInteractive == 1 ]; then
echo "Execution has completed; returning to command-line."
fi
else
$exCode=1
if [ $showInteractive == 1 ]; then
echo "In order to run this script either showInteractive or LogProgress need to be set to 1."
fi
fi
# Exit
exit $exCode