2

I want to establish a cron job in order to delete some files from a remote server in which I have only SFTP access. I don't have any shell access. What is the best way to connect to the remote server and do that? I have installed sshpass and did something like this:

sshpass -p pass sftp user@host

But how can I pass commands in order to list the old files and delete them?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user1919
  • 3,818
  • 17
  • 62
  • 97

2 Answers2

2

It's rather difficult to implement this using the OpenSSH sftp client.

You would have to:

  • list the directory using ls -l command;
  • parse the results (in shell or other script) to find names and times;
  • filter the files you want;
  • generate another sftp script to remove (rm) the files you found.

A way easier and more reliable would be to give up on the command-line sftp. Instead, use your favorite scripting language (Python, Perl, PHP) and its native SFTP implementation.

For an example, see:
Python SFTP download files older than x and delete networked storage

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
2

In Perl:

# untested:
my ($host, $user, $pwd, $dir) = (...);

use Net::SFTP::Foreign;
use Fcntl ':mode';

my $deadline = time - 24 * 60 * 60;

my $sftp = Net::SFTP::Foreign->new($host, user => $user, password => $pwd);
$sftp->setcwd($dir);
my $files = $sftp->ls('.',
# callback function "wanted" is passed a reference to hash with 3 keys for each file:
    # keys: filename, longname (like ls -l) and "a", a Net::SFTP::Foreign::Attributes object containing atime, mtime, permissions and size of file.
    # if true is returned, then the file is passed to the returned Array.
    # a similar function "no_wanted" also exists with the opposite effect.
                      wanted => sub {
                          my $attr = $_[1]->{a};
                          return $attr->mtime < $deadline and
                                 S_ISREG($attr->perm);
                      } ) or die "Unable to retrieve file list";

for my $file (@$files) {
    $sftp->remove($file->{filename})
        or warn "Unable to remove '$file->{filename}'\n";
}
salva
  • 9,943
  • 4
  • 29
  • 57