2009-10-07 4 views
9

Google 검색 및 오버플로가 조금 있었지만 사용할 수있는 파일을 찾을 수 없습니다.유닉스 ksh 쉘 스크립트 또는 perl 스크립트 및 트리거 펄 스크립트를 사용하여 새 파일을 모니터링하는 폴더

공용 폴더를 모니터링하고 새 파일을 만들 때 트리거를 실행하고 파일을 개인 위치로 이동시키는 스크립트가 필요합니다.

Windows의 X:\에 매핑 된 유닉스의 samba 공유 폴더 /exam/ple/가 있습니다. 특정 동작에서 txt 파일은 공유에 기록됩니다. 나는 폴더에 나타나는 txt 파일을 납치하여 유닉스의 개인 폴더 /pri/vate에 넣고 싶습니다. 그 파일을 옮기고 나면, 별도의 펄 스크립트를 실행시키고 싶다.

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

프로그래밍 방식으로 수행해야합니까, 아니면 기존 시설을 사용할 수 있습니까? 이것이 cron이 만들어진 것입니다. –

+0

새 파일로 cron을 트리거 할 수 있습니까? – CheeseConQueso

+0

나는 cron이 두 번 째 스크립트를 반복해서 실행하는 것을 원하지 않는다 ... 새 파일이 개인 폴더에 성공적으로 전송 된 후 두 번째 스크립트가 실행되기를 원한다. – CheeseConQueso

답변

9

확인 incron :

편집 아직도 사람이 어떤 아이디어 ... 새 파일을 모니터링하고 다음과 같이 실행됩니다 뭔가가있는 경우 쉘 스크립트를보기 위해 기다리고. 그것은 당신이 필요로하는 것을 정확하게하는 것처럼 보입니다.

+0

이것은 꽤 괜찮은 것처럼 보인다 ... 너무 나쁘다. 그것을 설치하지 마십시오 : < – CheeseConQueso

+0

큰 환영의 세계 유형의 incron의 예 : http://www.errr-online.com/2011/02/25/monitor-a-directory-or-file-for-changes-on- linux-using-inotify/ – mdaddy

+0

Windows에 incron을 설치할 수 있습니까? –

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

아픈 시험 그것 .... 이것은 무한히 추측한다 나는 짐작한다? 또한, 텍스트 파일 만 찾고 있지만 grep 폭탄은 멋지다. – CheeseConQueso

+1

@CheeseConQueso : 네, 지정한 주파수로 폴링하면서 무한 루프입니다. 코드를 엄격하게 테스트하지는 않았지만 아이디어는 충분히 간단합니다. –

+0

@CheeseConQueso : 상황에 따라 특정 접미어가 붙은 파일을 무시하도록 grep을 수정할 수 있습니다. –

1

이 IO의 공정한 비트가 발생합니다 - 합계는()를 호출 등이있다. link text 또는 link 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

여기에 온라인으로 찾은 korn 셸에서 30 초마다 검색을 수행하는 방법이있다. 새 파일, 더 많은 cron-type 프로세스 .... 새 파일이있는 상태에서 실행되는 korn 셸 스크립트를 찾을 수 없습니다. – CheeseConQueso

+0

@Cheese, 그게 좀 어설픈 예입니다. 두 파일이 있으면 in/exam/ple을 한 번 반복하면 본문이 두 번 실행되지만 두 파일은 처음으로 mv 될 것입니다. 그래서 mv의 두 번째 호출에서 에러를 보게 될 것입니다. 그 배꼽이 필요합니까? –

+0

@Martin - 좋은 지적 ... 온라인에서 찾았고 테스트하지 않았으므로 백틱이 필요한지 확실하지 않습니다. 쉘 방식이기 때문에 여기에 올렸습니다. 그것은 cron이 똑같은 일을 할 수 있다는 점에서 clunky입니다. – CheeseConQueso

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

장점 : 당신은 런타임 오버 헤드 (하지만 더 솔직 노력)없이 신속한 통지를하려면,/dnotify를 FAM 살펴보고 쉽게

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

이것은 매운 것 같습니다. 파이썬이 없지만, 네이티브 인 것에 대해 말하고있는 것에서, 나는 그것을 설치하고 시도해야 할 것입니다. thanks – CheeseConQueso

+0

CheeseConQueso : http://search.cpan.org/~drolsky/File-ChangeNotify-0.07/lib/File/ChangeNotify/Watcher/Inotify.pm 하위 클래스를 사용할 수 있고 File :: ChangeNotify가 @jsoversion에서 언급 한 경우 수행 할 수 있습니다. 같은 pyinotify. 빠른 CPAN 검색은 또 다른 가능한 해결책을 밝혀 냈습니다. http://search.cpan.org/~mlehmann/Linux-Inotify2-1.21/Inotify2.pm – jfs

+0

감사합니다 ... 나는 그것을 검사 할 것입니다. – CheeseConQueso

1

내가 KSH를 사용하지 않지만 내가 쉬와 함께 할 방법입니다. 나는 그것이 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

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

당신은 너무 당신이 어떤 스태킹 과정이없는, 이후의 스크립트 ($ 액션)에서 잠금 파일을 사용하고 출구에 그것을 정리할 것

.