2010-02-11 121 views
0

我想知道如何從我使用Net :: FTP在FTP服務器上設置的文件夾下載全部* .xml文件。我已經看到​​3210將是最好的方式,但我不能完全理解邏輯。如何通過FTP下載目錄中的所有XML文件?

基本上,我需要檢查文件夾中是否有XML文件。如果不是,請等待5秒鐘,然後再次檢查。一旦文件出現,我需要下載它們並通過Java應用程序運行它們(這一部分我已經陷入了困境)。

那麼,精彩的匿名助手,如何監控特定文件類型的文件夾,並在出現這些文件時自動生成ftp->get這些文件?

謝謝!

+0

是XML文件可變的?也就是說,他們是否在首次上傳後進行修改?如果是,那麼我假設你也需要下載更新的文件。正確? – aks 2010-02-12 14:16:11

回答

2

當我需要獲取FTP站點上的文件的過濾列表時,我使用grep和Net :: FTP的ls方法。

警告,未經測試的代碼:

#!/usr/bin/perl 

use strict; 
use warnings; 

use Net::FTP; 

#give END blocks a chance to run if we are killed 
#or control-c'ed 
$SIG{INT} = $SIG{TERM} = sub { exit }; 

my $host = shift; 
my $wait = 5; 

dbmopen my %seen, "files_seen.db", 0600 
    or die "could not open database: $!"; 

while (1) { 
    my $ftp = Net::FTP->new($host, Debug => 0) 
     or die "Cannot connect to $host: [email protected]"; 

    END { $ftp->quit if $ftp } #close ftp connection when exiting 

    $ftp->login("ftp",'ftp') #anonymous ftp 
     or die "Cannot login: ", $ftp->message; 

    for my $file (grep { /[.]xml$/ and not $seen{$_} } $ftp->ls) { 
     $ftp->get($file) 
      or die "could not get $file: ", $ftp->message; 
     #system("/path/to/javaapp", $file) == 0 
     # or die "java app blew up"; 
     $seen{$file} = 1; 
    } 
    sleep $wait; 
} 
+0

完美地工作,謝謝!現在我只需要克服Java應用程序中出現的一些問題...... – ryantmer 2010-02-12 20:15:01

0

這樣的事情呢?這當然會被你的代碼每X秒調用一次。

my %downloaded; 

sub check_for_new { 
    # Get all files 
    my @files = $ftp->ls; 

    foreach $f (@files) { 

     # Check if it is an XML file 
     if($f =~ /\.xml$/) { 

      # Check if you already fetched it 
      if(!$downloaded{$f}) { 

       if($ftp->get($f)) { 
        $downloaded{$f} = 1; 
       } else { 
        # Get failed 
       } 

      } 
     } 
    } 

} 
0

如果您需要重新下載,可能已經改變了,那麼你也需要做一個文件的XML文件進行比較,以確保您的本地副本同步與FTP服務器上的遠程複製。

use Cwd; 
use Net::FTP; 
use File::Compare qw(compare); 

my %localf; 
my $cdir = cwd; 

sub get_xml { 
    for my $file ($ftp->ls) { 
    ##Skip non-xml files 
    next if $file !~ m/\.xml$/; 

    ##Simply download if we do not have a local copy 
    if (!exists $localf{$file}) { 
     $ftp->get($file); 
     $localf($file) = 1; 
    } 
    ##else compare the server version with the local copy 
    else { 
     $ftp->get($file, "/tmp/$file"); 
     if (compare("$cdir/$file", "/tmp/$file") == 1) { 
     copy("/tmp/$file", "$cdir/$file"); 
     } 
     unlink "/tmp/$file"; 
    } 
    } 
} 

我輸入了這一點,直入回覆框所以它可能需要幾個潤色和錯誤檢查拋出在實施之前。對於外部邏輯,您可以編寫一個建立ftp連接的循環,調用該子例程,關閉連接並睡眠'n'秒。

相關問題