在远程服务器中使用 SFTP 删除超过一天的文件

Delete files older than one day with SFTP in remote server

我想建立一个 cron 作业,以便从我只有 SFTP 访问权限的远程服务器中删除一些文件。我没有任何 shell 访问权限。 连接到远程服务器并执行该操作的最佳方法是什么? 我已经安装了 sshpass 并做了这样的事情:

sshpass -p pass sftp user@host

但是我怎样才能通过命令来列出旧文件并删除它们呢?

使用 OpenSSH sftp 客户端实现这一点相当困难。

你必须:

  • 使用ls -l命令列出目录;
  • 解析结果(在 shell 或其他脚本中)以查找姓名和时间;
  • 过滤你想要的文件;
  • 生成另一个 sftp 脚本以删除 (rm) 您找到的文件。

一种更简单、更可靠的方法是放弃命令行 sftp。相反,请使用您最喜欢的脚本语言(Python、Perl、PHP)及其本机 SFTP 实现。

例如,参见:
Python SFTP download files older than x and delete networked storage

在 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";
}