skip to Main Content

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


  1. In your awk script make sure msg makes it to stdout:

    print msg
    

    Then outside your awk script add:

    | tee -a /var/log/server_mon.txt
    
    Login or Signup to reply.
  2. 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:

    awk '
        ...
        print msg | "cat>&2"
        print msg > "/var/log/server_mon.txt"
        ...
    '
    

    Remove print msg | "cat>&2" if you no longer need it.

    or to get both with one print:

    awk '
        ...
        print msg | "tee -a 47/var/log/server_mon.txt47 >&2"
        ...
    '
    

    or:

    awk '
        ...
        print msg
        ...
    ' | tee -a '/var/log/server_mon.txt' >&2
    

    or:

    awk '
        ...
        print msg | "cat>&2"
        ...
    ' 2> >(tee -a '/var/log/server_mon.txt' >&2)
    

    So many options….

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search