Home / code / shell

Example script,

This is a script that keeps track how often a piece of software is being run.
It logs it in a logfile, kills the offending process and email a listing of the offending process to someone.
This program will run constantly on your computer. You can start it and walk away, it will run until you manually stop it.

#!/bin/bash

echo -n "Enter a process name to watch for: "
read processname
echo -n "Enter a email address to warn when the process runs: "
read email

while true
do

  until ps axg |grep "$processname" | grep -s -v "grep" | grep -s -v "watcher" > /dev/null
  do
	sleep 5
  done

  dayandtime=`date`
  echo "$processname was running on $dayandtime" >> /var/log/watchprocess

  ps axgu | grep "$processname" | grep -v "grep" | /bin/mail -s "Uh oh!" "$email"
  killall -9 $processname
done

Ok now the explanation:

  • #!/bin/bash - Every script should start with this line (assuming you're using the bash shell). This tells the computer what interpreter it should be using to execute your script. We've been using bash so we need to tell the computer where to find it.

  • echo -n "Enter a process name to watch for: " - Prompt the user for a process name to watch.

  • read processname - Read in the variable processname

  • echo -n "Enter a email address to warn when the process runs: " - Prompt the user for an email address to send mail to.

  • read email - Read in the variable email.

  • while true - Create a while loop that will run indefinitely. This will keep the program running until you manually stop it. The true expression always evaluates true and can be used to create loops like this.

  • until ps axg |grep "$processname" | grep -s -v "grep" | grep -s -v "watcher" > /dev/null - Search for the process name to appear in the process listing.Execute an until loop until it does. Besides just avoiding the process we're looking for in the grep command, we now need to filter out the watcher command as well (the name of this script) because it is invoked with the process name that we're looking for and will generate a match in the until loop.

  • sleep 5 - Sleep for 5 seconds.

  • dayandtime=`date` - Store the output of the date command in the variable dayandtime.

  • echo "$processname was running on $dayandtime" >> /var/log/watchprocess - Print a message that the process was running and when it was running, redirect this massage to the file /var/log/watchprocess.

  • ps axgu | grep "$processname" | grep -v "grep" | /bin/mail -s "Uh oh!" "$email" - Find the line in process listing that shows who is running the evil process, pipe that line to the mail program and send it to the email address specified in email.

  • killall -9 $processname - Use killall to kill the process by process name.

 

TOP