4

In our linux server, we have a program running in the background which creates files in a certain directory. I want to get a mail when a new file is added to that dir.

I tried using Java, but that got to complex. So I'm looking for some better idea. Is there some program that can do this or a script?

Ed Niell
  • 43
  • 3

3 Answers3

4

Well, I'll go with overkill (is there such thing?) and suggest the utilities from the inotify-tools package.

More specifically the inotifywait tool:

# inotifywait -m /tmp
Setting up watches.  
Watches established.
/tmp/ OPEN,ISDIR 
/tmp/ CLOSE_NOWRITE,CLOSE,ISDIR 
.
.
.

Pipe its output through grep and send it to a Bash loop or something. Voila!

EDIT:

Here's a quick & dirty one-liner:

inotifywait -m /tmp 2>/dev/null | grep --line-buffered '/tmp/ CREATE' | while read; do echo update | mail -s "/tmp updated" john@example.com; done
thkala
  • 84,049
  • 23
  • 157
  • 201
2

You want inotify. You also might want superuser.com ;-)

Sdaz MacSkibbons
  • 27,668
  • 7
  • 32
  • 34
1

In this answer I list three Ruby libraries that let you watch a directory for changes. A script using one of these libraries and a mail library (like Pony) would be rather simple.

Using my library and Pony a script might be as simple as:

require 'directorywatcher'
require 'pony'

# Only watch every two minutes
my_watcher = Dir::DirectoryWatcher.new( 'uploads', 120 )
my_watcher.on_add = Proc.new do |file_name,info|
  Pony.mail(
    via:         :smtp,
    via_options: { address: 'smtp.mydomain.com', domain:'mydomain.com' },
    from:        "Upload Notifier <noreply@mydomain.com>",
    to:          "admin@mydomain.com",
    subject:     "New File Uploaded!",
    body:        "A new file '#{file_name}' was just uploaded on #{info[:date]}"
  )
end
my_watcher.start_watching.join # Join the thread
Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • +1 Thanks! Can this be left running in the background or do should I use it through cron? – Ed Niell Feb 01 '11 at 18:13
  • @EdNiell You can leave it running (with the modification I just added); I've not tested my library or the others I list in any mission-critical application, so you might want to keep an eye on it for a while. I do, however, have Ruby scripts running with the same pattern (spawn a thread and join it) that run in production for months at a time without issue. – Phrogz Feb 01 '11 at 19:45