mariog has asked for the wisdom of the Perl Monks concerning the following question:

Hello

I do not manage to copy the files on a remote sftp dir then once the file is copied and only if the copy is successful delete the file.

I have tried with net:sftp::foreign rget and get methods but they always complain that my localdir is a directory

#! /usr/bin/env perl use strict; use warnings; use feature qw(say); use autodie; use Net::SFTP::Foreign; use constant { HOST => "sftp.mariog.net", REMOTE_DIR => "/Daily", LOCAL_DIR => "/root", USER_NAME => "MGO", PASSWORD => "mypass", DEBUG => "0", }; my $sftp; $sftp = Net::SFTP::Foreign->new ( HOST, timeout => 240, user => USER_NAME, password => PASSWORD, autodie => 1, ); # # Fetch Files # $sftp->setcwd( REMOTE_DIR ); my @files = @{ $sftp->ls }; #Returns a reference to an array of hashe +s for my $file ( @files ) { $sftp->get($file->{filename}, LOCAL_DIR) or die "file transfer failed: " . $sftp->error; $sftp->remove( $file->{filename} ); } $sftp->disconnect;
thanks

Replies are listed 'Best First'.
Re: copy files on sftp to local dir and delete copied file
by choroba (Cardinal) on Sep 24, 2015 at 11:26 UTC
    but they always complain that my localdir is a directory
    Just guessing: so try to give them a file path?
    $sftp->get($file->{filename}, LOCAL_DIR . '/' . $file->{filename});
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Yes, that's right. Net::SFTP::Foreign requires the target argument to be the full file name.

      It favors predictability over DWIM.

      Hello

      that seems to work

      I needed to change the ls because it was still crashing due to . and .. directories.

      so I set like this:

      my @files = @{ $sftp->ls(no_wanted => qr/^\./)

      this seems to work okay..

      thanks alot.

        Are you sure you want to eliminate anything that begins with '.' (just asking, you very well might)? If not, it would likely be better to explicitly call out '.' and '..'.

        You may also want to consider what you mean by success. For example, are you certain the remote side is not being written to? There is a race condition between the get and the remove calls. OTOH, if the source location is unchanging (other than this script), you may be just fine.

        --MidLifeXis

Re: copy files on sftp to local dir and delete copied file
by Anonymous Monk on Sep 25, 2015 at 00:25 UTC
    Maybe the actual process you want to do is more like "rsync."

      +1

      Update: I guess a plus one doesn't mean anything here, but what I mean is I agree that rsync can probably provide a solution.

      Update 2: Specifically, I recommend trying Perl module File::Rsync.