use strict; use warnings; use Net::FTP; use DateTime (); use DateTime::Duration (); use File::Listing qw(parse_dir); use POSIX qw(strftime); use File::stat; my $pathto = "/mnt/tmp"; my $logname = "_log"; my ($host, $user, $passwd) = ('IP.ADD.RE.SS', 'user', 'password'); my $dir = '/common'; my $timesplit = 24; my $extension = '.tar'; my @noseries = ('monkey','dog','rubbit'); sub findstring { foreach my $series(@noseries) { if (index((lc $_[0]),(lc $series)) != -1) { return 1; } } return 0; } sub printclose { print MYOUTFILE localtime()."\: $_[0]\n"; close(MYOUTFILE); return "$_[0]\n"; } sub printfile { print MYOUTFILE localtime()."\: $_[0]\n"; return "$_[0]\n"; } my $now = DateTime->now; my $delta = DateTime::Duration->new( hours => $timesplit ); my $cutoff = $now->subtract_duration( $delta ); open(MYOUTFILE, '>>'.$pathto.$logname) or die "Impossibile creare o aprire il file di log"; #open for write, append print printfile('Avvio operazione'); print printfile('Mi connetto al server'); my $ftp = Net::FTP->new($host, Debug=> 1, Passive => 1 ) or die printclose("Non riesco a connettermi a $host"); print printfile('Effettuo il login'); $ftp->login($user, $passwd) or die printclose('Cannot login'); $ftp->binary(); print printfile('Seleziono la directory'); $ftp->cwd($dir) or die printclose('Cannot cwd to $dir'); print printfile('Cerco file da scaricare'); my $ls = $ftp->dir() or die printclose('Cannot list $dir'); foreach my $entry (parse_dir($ls)) { my ($name, $type, $size, $mtime, $mode) = @$entry; next unless ($type eq 'f' && ((lc (substr $name, -4)) cmp $extension) == 0 ); my $tz = DateTime::TimeZone->new( name => 'local' ); ( my $sec,my $min,my $hour,my $mday,my $months,my $year,my $wday,my $yday,my $isdst) = localtime($mtime); $year= $year+1900; $months=$months+1; my $dt = DateTime->new(year => $year, month => $months, day => $mday, hour => $hour, minute => $min, second => $min, time_zone => DateTime::TimeZone::Local->TimeZone()); my $cmp = DateTime->compare( $dt, $cutoff ); if ($cmp >=0) { if (findstring($name)==0) { print (printfile("Downloading $name")); $ftp->get($name,"$pathto$name")|| die printclose("get($name) failed: ". $ftp->code() . ": " . $ftp->message()); my $filesize = stat("$pathto$name")->size; if ($filesize!=$size) { print (printfile("Attenzione: File scaricato ma il size non corrisponde, possibile errore nel download")); } else { print (printfile("Scaricato con successo")); } } } } $ftp->quit; print printclose('Operazione completata con successo');