This script currently monitors a log file for keywords. Upon discovery of said keywords, the script then produces a message pertaining to the state of a server (up or down). It then outputs an email directly to me. The rest of the script just kills the script after a predetermined period of time.
Finally, what I’d like to do now is send the same info being sent to email, to a log file: emailoutput > /var/log/server_mon.txt
I’ve tried to use the cat and exec command to direct the printed messages to a file, but my syntax is wrong every time. Not really a programmer and not sure how or where exactly to apply the command. my guess is somewhere after “print” but again, not sure how.
#!/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
tail -fn0 /var/log/user | /usr/bin/awk '
/disconnect_tcp_conn/ { report("down") }
/daemon apps started/ { report("up") }
function report(curr_state, msg) {
if ( prev_state != curr_state ) {
msg = "Server is " curr_state
system("mail -s 47" msg " 47 [email protected] </dev/null")
print msg | "cat>&2"
prev_state = curr_state
}
}
'
&
PID=$!
DIEAT=`expr $SECONDS + 58`
while [ -d /proc/$PID ] && [ "$SECONDS" -lt "$DIEAT" ]
do
sleep 1
done
[ -d /proc/$PID ] && kill "$PID"
wait
Expected result is to have whats being output to email, to a text file for the purpose of keeping track of how often the script is reporting the servers condition.
I’m running this script on centos 5.5 btw..
2
Answers
In your awk script make sure msg makes it to stdout:
Then outside your awk script add:
print msg | "cat>&2"
is printing the message to stderr. Do you want to print it to/var/log/server_mon.txt
instead of stderr or in addition to stderr?There’s a lot of options including:
Remove
print msg | "cat>&2"
if you no longer need it.or to get both with one
print
:or:
or:
So many options….