2

I am connecting SFTP and downloading the file using perl. I want to download the file that is created/modified 1 hours back.

The below is code snippet.

use strict;
use Net::SFTP::Foreign;
my $sftp_conn=Net::SFTP::Foreign->new('test.sftp.com',user=>'test',password=>'test123');
my $a1 = Net::SFTP::Foreign::Attributes->new();
my $a2 = $sftp_conn->stat('/inbox/tested.txt') or die "remote stat command failed: ".$sftp_conn->status;
$sftp_conn->get("/inbox/tested.txt","/tmp"));

Here I want to check the file age at what time it modified and calculate in hours.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Madhan
  • 1,291
  • 3
  • 21
  • 34

1 Answers1

4

You are on the right track. Calling ->stat on the connection object returns a Net::SFTP::Foreign::Attributes object. You can then call ->mtime on it to get the modifcation time.

my $attr = $sftp_conn->stat('/inbox/tested.txt') 
    or die "remote stat command failed: ".$sftp_conn->status;
print $attr->mtime;

There is no need to create an empty object first. You don't need the following line. You probably copied it from the SYNOPSIS in the docs, but that's just to show different ways of using that module. You can delete it.

my $a1 = Net::SFTP::Foreign::Attributes->new();

I don't know which format the mtime will be in, so I can't tell you how to do the comparison. There is nothing about that in the docs, in the code of the module or in the tests.

A quick google suggested "YYYYMMDDhhmmss", but that might not be the right one. Just try it. If it's a unix timestamp, you can just compare it to time or time - 3600, but if it's a string, you will need to parse it. Time::Piece is a useful module that comes with the Perl core to do that.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 2
    `mtime` and `atime` are in Unix time; the number of seconds elapsed since the epoch (00:00:00, 1 January 1970 UTC). I will add a note in the docs explaining it. – salva May 12 '17 at 16:41
  • @salva sweet, thank you! :) Good to hear from a module author directly. – simbabque May 12 '17 at 16:43