-1

I looked at this topic to write a bash script that checks if a file has been modified every 60 min and sends me an email using ssmtp if that is the case. Here is its content (monitoring.sh):

#!/bin/bash

[[ -z `find /home/myuser/sites/mysite/logs/nginx/error.log -mmin -60` ]]

if [ $? -eq 0 ]
then
    echo -e "nothing has changed"
else
    echo -e "Something went wrong!" | ssmtp -vvv myemail@gmail.com
fi

I then added this script to an hourly cronjob:

 01 * * * * /home/myuser/sites/mysite/logs/nginx/monitoring.sh

This does not work at all. Looking at my emails (the sender account that ssmtp uses), the script runs every hour and echoes nothing has changed even if the error.log file has been modified.

Maybe using inotifywait would be more appropriate? Any ideas?

Thanks in advance.

EDIT: If I run this script manually after modifying the error.log file, it works and I receive the email.

David B.
  • 466
  • 1
  • 3
  • 12
  • Your problem really has nothing to do with cron. – user9517 Aug 03 '16 at 17:07
  • I would not use inotify. I would enable a very explicit auditd rule to tell me who and / or what is changing that file and the exact time it happens. You could use auditd plugins to send you the alert, or send it to syslog with the audisp plugin and have monitoring tools alert you. – Aaron Aug 03 '16 at 17:34
  • I think you want single `[`, not double (you're doing a test(1), you're not doing math. – Cameron Kerr Aug 04 '16 at 09:18

1 Answers1

2

The -mmin option as you used it matches an exact number of minutes, not a "within this range" number of minutes. See this example:

$ touch foo
$ find . -mmin 1
.
./foo
$ find . -mmin 10
$

What you want is to use a value of -10 instead of 10:

$ touch foo
$ find . -mmin -10
.
./foo

And you'll probably want to give it the -type flag as well to only match files, not directories:

$ find . -type f -mmin -10
./foo
EEAA
  • 109,363
  • 18
  • 175
  • 245
  • Thanks for the detailed answer! Correct me if I am wrong but since I cannot specify a range, this type of script won't work for me since I do not know when the file will be modified? – David B. Aug 03 '16 at 19:53
  • 2
    Well, if you're running this every 10 minutes, you'd check for files modified in the last 10 minutes. I would perhaps recommend a different approach, though. Take an md5 of the file, write it to disk somewhere, then check that md5 on the next run. If the md5 of the file is different, send an alert. This method is much more foolproof than a time-based approach. – EEAA Aug 03 '16 at 20:08
  • 1
    and this (checksum verification) is already provided f.e. by the tool "tripwire", just if you want to have an already working solution for exactly that issue. – Dennis Nolte Aug 04 '16 at 07:53
  • @EEAA thanks, looking into this. Dennis Nolte, thank you, also looked at tripwire but not entirely sure how to proceed with that. – David B. Aug 04 '16 at 15:53