我想建立一个cron作业,以便从我只有SFTP访问权限的远程服务器中删除一些文件。我没有任何shell访问权限。
连接到远程服务器的最佳方法是什么?
我安装了superview
并执行了类似的操作:
sshpass
但是如何传递命令以列出旧文件并将其删除?
答案 0 :(得分:2)
使用OpenSSH sftp
客户端实现此功能相当困难。
你必须:
ls -l
命令列出目录; sftp
脚本以删除(rm
)您找到的文件。更简单,更可靠的方法是放弃命令行sftp
。相反,请使用您喜欢的脚本语言(Python,Perl,PHP)及其本机SFTP实现。
答案 1 :(得分:2)
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";
}