使用unix ksh shell脚本或perl脚本和触发perl脚本监视新文件的文件夹

时间:2009-10-07 20:17:15

标签: perl unix shell ksh

我一直在谷歌搜索和溢出,找不到任何可用的东西。

我需要一个监视公用文件夹的脚本,并在新文件创建时触发,然后将文件移动到私有位置。

我在unix上有一个samba共享文件夹/exam/ple/,映射到Windows上的X:\。在某些操作上,txt文件将写入共享。我想绑定文件夹中出现的任何txt文件,并将其放在unix上的私人文件夹/pri/vate中。移动该文件后,我想触发一个单独的perl脚本。

修改的 还有等待看到shell脚本,如果有人有任何想法...将监视新文件,然后运行类似的东西:

#!/bin/ksh
mv -f /exam/ple/*.txt /pri/vate

8 个答案:

答案 0 :(得分:9)

检查incron。它似乎完全符合你的需要。

答案 1 :(得分:6)

如果我理解正确,你只想要这样的东西?

#!/usr/bin/perl

use strict;
use warnings;

use File::Copy

my $poll_cycle = 5;
my $dest_dir = "/pri/vate";

while (1) {
    sleep $poll_cycle;

    my $dirname = '/exam/ple';

    opendir my $dh, $dirname 
        or die "Can't open directory '$dirname' for reading: $!";

    my @files = readdir $dh;
    closedir $dh;

    if ( grep( !/^[.][.]?$/, @files ) > 0 ) {
        print "Dir is not empty\n";

        foreach my $target (@files) {
            # Move file
            move("$dirname/$target", "$dest_dir/$target");

            # Trigger external Perl script
            system('./my_script.pl');
    }
}

答案 2 :(得分:5)

File :: ChangeNotify允许您监视文件和目录以进行更改。

https://metacpan.org/pod/File::ChangeNotify

答案 3 :(得分:3)

我知道,我迟到了派对,但为了完整性并为未来的访客提供信息;

#!/bin/ksh
# Check a File path for any new files
# And execute another script if any are found

POLLPATH="/path/to/files"
FILENAME="*.txt" # Or can be a proper filename without wildcards
ACTION="executeScript.sh argument1 argument2"
LOCKFILE=`basename $0`.lock

# Make sure we're not running multiple instances of this script
if [ -e /tmp/$LOCKFILE ] ; then 
     exit 0
else
     touch /tmp/$LOCKFILE
fi

# check the dir for the presence of our file
# if it's there, do something, if not exit

if [ -e $POLLPATH/$FILENAME ] ; then
     exec $ACTION
else
     rm /tmp/$LOCKFILE
     exit 0
fi

从cron运行它;

*/1 7-22/1 * * * /path/to/poll-script.sh >/dev/null 2>&1

你想在后续脚本($ ACTION)中使用lockfile,然后在退出时清理它,这样你就没有任何堆叠过程。

答案 4 :(得分:2)

$ python autocmd.py /exam/ple .txt,.html /pri/vate some_script.pl

优点:

autocmd.py

#!/usr/bin/env python
"""autocmd.py 

Adopted from autocompile.py [1] example.

[1] http://git.dbzteam.org/pyinotify/tree/examples/autocompile.py

Dependencies:

Linux, Python, pyinotify
"""
import os, shutil, subprocess, sys

import pyinotify
from pyinotify import log

class Handler(pyinotify.ProcessEvent):
    def my_init(self, **kwargs):
        self.__dict__.update(kwargs)

    def process_IN_CLOSE_WRITE(self, event):
        # file was closed, ready to move it
        if event.dir or os.path.splitext(event.name)[1] not in self.extensions:
           # directory or file with uninteresting extension
           return # do nothing

        try:
            log.debug('==> moving %s' % event.name)
            shutil.move(event.pathname, os.path.join(self.destdir, event.name))
            cmd = self.cmd + [event.name]
            log.debug("==> calling %s in %s" % (cmd, self.destdir))
            subprocess.call(cmd, cwd=self.destdir)
        except (IOError, OSError, shutil.Error), e:
            log.error(e)

    def process_default(self, event):
        pass


def mainloop(path, handler):
    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, default_proc_fun=handler)
    wm.add_watch(path, pyinotify.ALL_EVENTS, rec=True, auto_add=True)
    log.debug('==> Start monitoring %s (type c^c to exit)' % path)
    notifier.loop()


if __name__ == '__main__':
    if len(sys.argv) < 5:
       print >> sys.stderr, "USAGE: %s dir ext[,ext].. destdir cmd [args].." % (
           os.path.basename(sys.argv[0]),)
       sys.exit(2)

    path = sys.argv[1] # dir to monitor
    extensions = set(sys.argv[2].split(','))
    destdir = sys.argv[3]
    cmd = sys.argv[4:]

    log.setLevel(10) # verbose

    # Blocks monitoring
    mainloop(path, Handler(path=path, destdir=destdir, cmd=cmd,
                           extensions=extensions))

答案 5 :(得分:1)

这将导致相当多的io-stat()调用等。如果您想在没有运行时开销的情况下快速通知(但需要更多的前期工作),请查看FAM / dnotify:link textlink text

答案 6 :(得分:1)

我不使用ksh,但这是我用sh做的方式。我确信它很容易适应ksh。

#!/bin/sh
trap 'rm .newer' 0
touch .newer
while true; do
  (($(find /exam/ple -maxdepth 1 -newer .newer -type f -name '*.txt' -print \
      -exec mv {} /pri/vate \; | wc -l))) && found-some.pl &
  touch .newer
  sleep 10
done

答案 7 :(得分:0)

#!/bin/ksh
while true
do
    for file in `ls /exam/ple/*.txt`
    do
          # mv -f /exam/ple/*.txt /pri/vate
          # changed to
          mv -f  $file  /pri/vate

    done
    sleep 30
done