添加文件时运行 shell 命令 [英] Run a shell command when a file is added
问题描述
我的 linux 机器上有一个名为 images 的文件夹.该文件夹连接到一个网站,该网站的管理员可以向该网站添加图片.但是,当添加图片时,我想要一个命令来运行调整目录中所有图片的大小.
I have a folder named images on my linux box. This folder is connected to a website and the admin of the site has the ability to add pictures to this site. However, when a picture is added, I want a command to run resizing all of the pictures a directory.
简而言之,我想知道如何在将新文件添加到特定位置时让服务器运行特定命令.
In short, I want to know how I can make the server run a specific command when a new file is added to a specific location.
推荐答案
我不知道人们如何将内容上传到此文件夹,但您可能想要使用比使用 inotify 监控目录技术更低的技术.
I don't know how people are uploading content to this folder, but you might want to use something lower-tech than monitoring the directory with inotify.
如果协议是 FTP 并且您可以访问您的 FTP 服务器的日志,我建议拖尾该日志以观察成功上传.与使用传统 cron 的轮询方法相比,这种事件触发的方法将更快、更可靠且负载更少,并且比使用 inotify 的方法更便携且更易于调试.
If the protocol is FTP and you have access to your FTP server's log, I suggest tailing that log to watch for successful uploads. This sort of event-triggered approach will be faster, more reliable, and less load than a polling approach with traditional cron, and more portable and easier to debug than something using inotify.
您处理此问题的方式当然取决于您的 FTP 服务器.我有一个运行 vsftpd 的日志包括这样的行:
The way you handle this will of course depend on your FTP server. I have one running vsftpd whose logs include lines like this:
Fri May 25 07:36:02 2012 [pid 94378] [joe] OK LOGIN: Client "10.8.7.16"
Fri May 25 07:36:12 2012 [pid 94380] [joe] OK UPLOAD: Client "10.8.7.16", "/path/to/file.zip", 8395136 bytes, 845.75Kbyte/sec
Fri May 25 07:36:12 2012 [pid 94380] [joe] OK CHMOD: Client "10.8.7.16", "/path/to/file.zip 644"
只有当 vsftpd 成功保存文件时,才会添加 UPLOAD
行.您可以在这样的 shell 脚本中解析它:
The UPLOAD
line only gets added when vsftpd has successfully saved the file. You could parse this in a shell script like this:
#!/bin/sh
tail -F /var/log/vsftpd.log | while read line; do
if echo "$line" | grep -q 'OK UPLOAD:'; then
filename=$(echo "$line" | cut -d, -f2)
if [ -s "$filename" ]; then
# do something with $filename
fi
fi
done
如果您使用的是 HTTP 上传工具,请查看该工具是否具有用于记录传入文件的文本日志文件.如果它不考虑向其添加某种记录器功能,那么它会生成您可以tail
的日志.
If you're using an HTTP upload tool, see if that tool has a text log file it uses to record incoming files. If it doesn't consider adding some sort of logger function to it, so it'll produce logs that you can tail
.
这篇关于添加文件时运行 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!