【发布时间】:2011-06-19 11:07:46
【问题描述】:
在我们的 linux 服务器中,我们有一个在后台运行的程序,它在某个目录中创建文件。当新文件添加到该目录时,我想收到一封邮件。
我尝试使用 Java,但这变得很复杂。所以我正在寻找更好的主意。有没有可以做到这一点的程序或脚本?
【问题讨论】:
标签: linux shell directory notifications
在我们的 linux 服务器中,我们有一个在后台运行的程序,它在某个目录中创建文件。当新文件添加到该目录时,我想收到一封邮件。
我尝试使用 Java,但这变得很复杂。所以我正在寻找更好的主意。有没有可以做到这一点的程序或脚本?
【问题讨论】:
标签: linux shell directory notifications
好吧,我会选择矫枉过正(有这样的事情吗?)并建议来自inotify-tools package 的实用程序。
更具体地说是inotifywait 工具:
# inotifywait -m /tmp
Setting up watches.
Watches established.
/tmp/ OPEN,ISDIR
/tmp/ CLOSE_NOWRITE,CLOSE,ISDIR
.
.
.
通过grep 将其输出传送到 Bash 循环或其他东西。瞧!
编辑:
这是一个快速而肮脏的单线:
inotifywait -m /tmp 2>/dev/null | grep --line-buffered '/tmp/ CREATE' | while read; do echo update | mail -s "/tmp updated" john@example.com; done
【讨论】:
你想要inotify。你也可能想要superuser.com ;-)
【讨论】:
在this answer 中,我列出了三个 Ruby 库,可以让您监视目录的更改。使用其中一个库和邮件库(如Pony)的脚本会相当简单。
使用my library 和 Pony 的脚本可能很简单:
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
【讨论】: