Reputation: 43
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?
Upvotes: 4
Views: 821
Reputation: 303136
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 <[email protected]>",
to: "[email protected]",
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
Upvotes: 1
Reputation: 86333
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" [email protected]; done
Upvotes: 4