# record log search start
echo "Search for->" $1 "starting" `date '+%r'` >>$log_report
echo "" >>$log_report
# get and save grep results of keyword ($1) from logfile ($2)
grep -i $1 $2 >>$log_report
# build report footer with time
echo "" >>$log_report
echo "End of" $log_report at `date '+%r'` >>$log_report
# mail report to root
mail -s "Log Analysis for $1" root <$log_report
# clean up and remove report
rm $log_report
exit 0
In this example, the script creates the variable $log_report, which will be
the filename of the temporary report. The keyword ($1) and first argument on
the command line are used as part of the filename, along with the current date
(with perhaps a better approach being to use $$ instead of the date, which
will append the script’s PID as a file extension). Next, the report header
containing some formatted text, the output of the uname command, and the
hostname and date are added to the report. The start of the search is then
recorded, and any matches of the keyword in the log are added to the report.
A footer containing the name of the report and the time is then added. The
report is mailed to root with the search term as the subject of the message, and
the temporary file is deleted.
You can test the script by running it manually and feeding it a keyword and a
pathname to the system log, /var/log/messages, like this:
Click here to view code image
matthew@seymour:~$ sudo greplog FAILED /var/log/messages
Note that your system should be running the syslogd daemon. If any login
failures have occurred on your system, the root operator might get an email
message that looks like this:
Click here to view code image
Date: Sun, 23 Oct 2016 16:23:24 -0400
From: root [email protected]
To: [email protected]
Subject: FAILED
==============================================================