R – How to login to an FTP site and remove files that are more than 7 days old

ftpperl

I need a shell or Perl script which would connect to the FTP server and delete all the files which are more than 7 days old.

cheers

Best Solution

Use the Net::FTP module to connect to the ftp server as outlined in the CPAN document. To browse through the site listings you may have to combine cwd/cdup in order to handle directories (unless ofcourse all the files are in the root directory).

To get the file's modification time use the mdtm(FILE) method, just make sure to check if this is supported on the current server by calling

if( $ftp->feature( 'MDTM' ) ) {
   ...check modification time for file...
}

If not, then you might try calling the 'dir' method which will get you the listings in the long format, and then extract the date information from the individual file listings in order to compare and delete.

To compare the two dates use the Date::Calc module. The 'Delta_Days' method should give you the number of days between two dates; this can be used just as easily for either of the methods specified above.