2009-10-07 82 views
9

我一直在谷歌搜索和溢出了一下,找不到任何可用的东西。使用unix ksh shell脚本或perl脚本监控新文件夹并触发perl脚本

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

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

编辑 仍观望shell脚本,如果任何人有任何想法...的东西,将监测的新文件,然后运行是这样的:

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

您是否需要通过编程的方式来完成它,还是可以利用现有的设施?这是cron的目标。 – 2009-10-07 20:19:43

+0

可以通过新文件触发cron吗? – CheeseConQueso 2009-10-07 20:21:40

+0

我也不希望cron反复运行第二个脚本...我只希望第二个脚本在新文件成功转移到私人文件夹后运行 – CheeseConQueso 2009-10-07 20:27:18

回答

9

检查incron。它似乎正是你所需要的。

+0

这看起来相当不错...我可以安装它:< – CheeseConQueso 2009-10-08 19:25:48

+0

incron的一个很棒的hello world类型示例:http://www.errr-online.com/2011/02/25/monitor-a-directory-or-file-for-changes-on- linux-using-inotify/ – mdaddy 2012-01-04 03:01:59

+0

可以在Windows上安装incron吗? – 2013-09-26 19:05:19

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'); 
    } 
} 
+0

虐待它测试....这运行无限im猜测?另外,即时通讯只寻找文本文件,但grep炸弹很酷,有 – CheeseConQueso 2009-10-07 20:41:14

+1

@ CheeseConQueso:是的,这是一个无限的循环,按您指定的频率进行轮询。我没有严格测试代码,但这个想法很简单。 – 2009-10-07 20:45:25

+0

@CheeseConQueso:如果这是你的情况,你显然可以修改'grep'来忽略带有特定后缀的文件。 – 2009-10-07 20:46:17

1

这将导致IO公平一点 - STAT()调用等。如果您想在不运行时开销(但更多的前期工作)迅速通知,看一看FAM/dnotify:link textlink text

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 
+0

小时这里是一种方法来做一个搜索每30秒钟korn shell,我在网上找到....它不是由触发一个新的文件,它更多的是一个cron类型的过程....我仍然无法找到一个运行在新文件存在的korn shell脚本 – CheeseConQueso 2009-10-08 15:02:24

+0

@Cheese,这是一个笨重的例子 - 如果有两个文件在一次迭代中,对于身体将运行两次,但是这两个文件将首次被mv'ed。所以你会在第二次调用MV时看到错误。这些反引号是否需要? – 2009-10-11 20:53:45

+0

@Martin - 好点...我在网上找到它,并没有对它进行测试,所以我不确定是否需要反引号。我只是把它放在这里,因为它是一个shell方法。这也是笨重的,因为cron可以做同样的事情 – CheeseConQueso 2009-10-12 12:55:08

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)) 
+0

这看起来很辛辣....我没有python,但是从你所说的关于通知是原生的,我可能不得不安装它并尝试一下。 。谢谢 – CheeseConQueso 2009-10-08 19:57:34

+0

CheeseConQueso:如果http://search.cpan.org/~drolsky/File-ChangeNotify-0.07/lib/File/ChangeNotify/Watcher/Inotify.pm子类可用,那么@jsoversion提到的File :: ChangeNotify可以做与pyinotify相同。快速CPAN搜索揭示了另一种可能的解决方案http://search.cpan.org/~mlehmann/Linux-Inotify2-1.21/Inotify2.pm – jfs 2009-10-08 20:36:37

+0

谢谢...我将检查出 – CheeseConQueso 2009-10-08 20:44:01

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 
+0

谢谢,虐待尝试转换语法和试试看 – CheeseConQueso 2011-01-21 16:08:25

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),然后清理退出,只是让你没有任何堆放过程。