2

I'm using WebInject (CLI not GUI) to test out online web services. I was going to go with a third party until I found this little gem and realized what I could save...

What I want to accomplish is to grep the results of WebInject (Perl script) . If it finds a pattern then pipe the results to mail. I'm new at this and am not quite sure how to write the logic for evaluating the results and sending it to mail.

This is what I have so far:

$ perl webinject.pl | grep 'TEST CASE FAILED'

I only want to send an email if grep finds a match, otherwise no email should be sent. I'd like to set this up with cron to run at 10 or 15 minute intervals.

As a side note, is grep able to grab leading and trailing characters from a matching pattern?

UPDATE 1: figured out leading and trailing lines (-A # -B #)

Thanks very much!

2 Answers 2

2

Take a look to this answer echo based on grep result
It's almost the same, take the answer that better fit your need then suppress the echo No part and remplace the echo yes part by an email command

Regading leading and trailing characters you can use -C options or -A and -B (-C is -A X -B X)

   -A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  Places a line containing -- between contiguous groups of matches.


   -B NUM, --before-context=NUM
          Print NUM lines of leading context before matching lines.  Places a line containing -- between contiguous groups of matches.

   -C NUM, --context=NUM
          Print NUM lines of output context.  Places a line containing -- between contiguous groups of matches.

if I understand what you want to do, you might like the following exemple

perl webinject.pl > /tmp/webinject_result.txt
if grep --quiet 'TEST CASE FAILED' /tmp/webinject_result.txt;
then
  grep -B 20 -B 2 'TEST CASE FAILED' /tmp/webinject_result.txt | mail [email protected]
fi
1
  • Wow, works like a charm!! Thanks a lot. I had already looked at the first answer you provided but still wasn't able to figure it out. This is great and I'll be able to modify it to no end. Thanks!
    – JohnyD
    Jun 22, 2010 at 16:51
3

Here's a one-liner which should work:

perl webinject.pl | grep 'TEST CASE FAILED' 2>&1 > /tmp/grep.log && /usr/bin/mail -s "grep found something" [email protected] < /tmp/grep.log

Here is a more generic case, with multiple commands:

{ COMMAND1 ; COMMAND2 |grep 'your string here' ; } 2>&1 > /tmp/logfile && /usr/bin/mail -s "$SUBJECT" $MAILTO < /tmp/logfile

The code after the && will only activate if the command within the curly-braces finds a match (The return code is zero, which means success). I use the 2>&1 to make sure I don't miss any output.

You can also output this information to syslog. See Better logging for cronjobs? Send cron output to syslog?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .