Grepping and only sending emails if something is found

#!/bin/bash ( /usr/src/chkrootkit-$VERSION/chkrootkit ) | # Binary grep 'INFECTED|Vulnerable' | # Only get found issues /bin/mail -s 'CHROOTKIT Weekly Run ($SERVERNAME)' $EMAIL # Send EMail 

It still sends emails even if nothing is found.

How can I send only a message if something was grepped?

+4
source share
3 answers

It could be ...

Just use the -E switch in the mail command:

 man -Pcol\ -b mail | grep empty -E Don't send messages with an empty body. #!/bin/bash ( /usr/src/chkrootkit-$VERSION/chkrootkit ) | # Binary grep 'INFECTED|Vulnerable' | # Only get found issues /bin/mail -E -s 'CHROOTKIT Weekly Run ($SERVERNAME)' $EMAIL # Send EMail 

or put your check in crontab for automatic processing, for example, once a day:

 @daily ( /usr/src/chkrootkit-$VERSION/chkrootkit ) | grep 'INFECTED|Vulnerable' 

Cron will send mail if the command issues something.

But after reading this again

If there is no need to forward any part of the mail in the notification, there is no need to use the pipe | .

So you can use the condition as follows:

 #!/bin/bash ( /usr/src/chkrootkit-$VERSION/chkrootkit ) | # Binary grep -q 'INFECTED|Vulnerable' && /bin/mail -s 'CHROOTKIT Weekly Run ($SERVERNAME)' $EMAIL 

The -q switch to grep provides peace of mind.

+6
source

For GNU Mailutils, you can do something like this with -E'set nonullbody :

 grep whatever wherever | mailx -E'set nonullbody' -s EMAIL_SUBJECT your_email_address@example.com 

See http://mailutils.org/manual/html_section/mail.html : nullbody

Type: Boolean
Default: True

Controls whether mail accepts messages with an empty body. The default value, true, means that such messages are sent, and a warning appears (traditionally saying "The body of the message is Null, I hope this is normal"). The warning text can be set using the nullbodymsg variable (see below).

If nullbody is not set, mail will silently ignore such messages. This can be useful in crontab files to avoid sending emails when nothing happens. For example, the "crontab" entry below sends mail only if the some-prog utility outputs something to its standard output or error:

Just put the above in cron for some graph:

 */5 * * * * some-prog 2>&1 | /bin/mail -E'set nonullbody' -s 'Periodic synchronization' 
+4
source
 #!/bin/bash ( /usr/src/chkrootkit-$VERSION/chkrootkit ) | # Binary grep 'INFECTED|Vulnerable' # Only get found issues if [ $? -eq 0 ] /bin/mail -s 'CHROOTKIT Weekly Run ($SERVERNAME)' $EMAIL # Send EMail fi 

grep returns a non-zero exit code if it finds a match, 0 if it is not. We just need to check the last return value (this is the return value of grep) and conditionally send mail based on this.

+1
source

All Articles