Run a shell command when a file is added

前端 未结 6 521
梦毁少年i
梦毁少年i 2020-11-27 20:04

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

6条回答
  •  渐次进展
    2020-11-27 20:20

    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.

    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.

    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"
    

    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
    

    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.

提交回复
热议问题