![](/img/trans.png)
[英]Perl using Net::SFTP::Foreign get rid of server welcome message
[英]Perl Net::SFTP::Foreign to get latest file from remote server
我正在尝试使用 Perl Net::SFTP::Foreign
模块将文件从远程服务器传输到本地服务器。
这是我的代码:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Net::SFTP::Foreign;
my $host = "host.ip.address.here";
my $user = "username";
my $pass = "password";
my $path = "/path/to/the/remote/server/directory";
my $local_dir = "/local/dir/path/";
my $sftp = Net::SFTP::Foreign->new(host=>$host , user=>$user , password=>$pass);
$sftp->die_on_error("Unable to establish SFTP connection");
$sftp->setcwd($path) or die "unable to change cwd: " . $sftp->error;
my @file = $sftp->ls($path);
print Dumper(\@file);
$sftp->mget("$path/test*.csv", $local_dir);
我的远程服务器中有文件列表-
test123.csv
test234.csv
test341.csv
test890.csv
test765.csv
test110.csv
这里的事情是我想从$path
目录中获取最新文件,该文件基于修改日期。 (我无法找到解决方案)
有什么命令可以做到这一点吗?
我发现的其他方法是循环@files
数组,但我如何获取最新文件? 此外,我不想循环,因为$path
有很多文件需要很长时间才能执行。
所以我想使用一个命令来获取远程文件。 任何想法?
看看文档的 $sftp->stat($ path_or_fh ) 方法
它返回有关文件的属性列表,包括 mtime。 您必须为您提取的每个文件获取 mtime 并通过最新文件上的代码做出决定。
我找到了以下解决方案。 在这里发布我的答案,这样它可以帮助寻找类似要求的人。
以下是上述(有问题的)脚本的延续代码。
my %filehash;
foreach (@$files){
my $file = $_->{filename};
next unless($file =~ m/test(.*)\.csv/);
my $stat_attr = $sftp->stat($file) or die "remote stat command failed: ".$sftp->status;
my $size = $stat_attr->size;
my $mtime = $stat_attr->mtime;
$filehash{$file}{'MTIME'} = $mtime;
}
my $recent_file = List::Util::reduce { $filehash{$b} > $filehash{$a} ? $b : $a } keys %filehash;
print "Recent FILE:$recent_file, TIME:$filehash{$recent_file}{'MTIME'}\n";
$sftp->mget("$path$recent_file", $local_dir);
$sftp->disconnect;
系统应支持List::Util;
perl 模块,应该在脚本的开头使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.