Tag Archives: hetzner

Deleting files older than N days from FTP server

Many hosting companies provide customers with FTP space for storing their backups (e.g. Hetzner, HostEurope).

Problem is that unless you want the backup space to fill up after a while you have two possibilities:

  • use a naming scheme for your backups which overwrites old files like hostname-DAYOFWEEK.tar.gz, hostname-DAYOFMONTH.tar.gz
  • automatically delete old files from your FTP space

I like to name my backups with the full date, e.g. hostname-YYYY-MM-DD.tar.gz, so I went for the latter.

Unfortunately deleting old files from an FTP server is not as simple as running find . -mtime +30 -delete because usually you don’t get shell access to your FTP space. Everything must be done via FTP.

Here comes a simple perl script I wrote that does the trick. It requires the Net::FTP module.

Hope it will be useful to you too!

use strict;
use Net::FTP;

my $host        = "ftp.hostname.com";
my $dir         = "/";
my $user        = "foo";
my $passwd      = "bar";
my $interval    = 3600*24*62; # 62 day
my $passive     = 1; # my FTP server only works in PASV mode
my $DEBUG       = 0;

my $ftp = Net::FTP->new($host,
 Debug => $DEBUG,
 Passive => $passive)
 or die "Can't open $host\n";
$ftp->login($user, $passwd) or die "Can't log in as $user\n";
$ftp->cwd($dir) or die "Can't chdir to $dir\n";
my @files = $ftp->ls();

foreach my $file (@files) {
my $file_mdtm = $ftp->mdtm($file) or die "Can't find $file in $dir\n";
if (time - $file_mdtm >= $interval) {
print "File $file is older than $interval secs: deleted\n";
$ftp->delete($file) unless $DEBUG;

The password is stored in the script itself so make sure permissions are set properly! You don’t want it to be world readable :)

chmod 700 ./ftp-purge-backups.pl