简体   繁体   中英

Perl Net::SFTP::Foreign to get latest file from remote server

I am trying to transfer file from remote server to local server using Perl Net::SFTP::Foreign module.

Here is my code:

#!/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); 

I have list of files in my remote server -

test123.csv
test234.csv
test341.csv
test890.csv
test765.csv
test110.csv

The thing here is I want to get the latest file from $path directory, which is based on modification date. (I am unable to find the solution)

Is there any command which can achieve this?

Other method I found is loop through @files array but how do I get the latest file? Moreover I don't want to loop through, because $path have lots of files which will take much time to execute.

So I wanted to get the remote file using a single command. Any idea?

Have a look at the $sftp->stat($path_or_fh) method of the docs

It returns a list of attributes about the file, including mtime. You'll have to get the mtime for each file you pull and make a decision via code on the latest file.

I found following solution. Posting my answer here, so it could help people looking for similar kind of requirement.

Below is the code which is continuation of above (questioned) script.

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;

System should support List::Util; perl module which should be used in the begining of the script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM