简体   繁体   中英

Transferring Directories using sftp foreign module in Perl

I am trying to transfer all the directories and its contents from sftp to unix server and delete all the transferred files from SFTP server. I am using rget method in SFTP::Foreign module for this purpose. But when i run the below code, i keep getting an error. Please help.

use Net::SFTP::Foreign;

use constant {
    HOST       => "Host name",
    REMOTE_DIR => "sample/remote",
    LOCAL_DIR  => "sample/local",
    USER_NAME  => "username",
    PASSWORD   => "password",
    DEBUG      => "0",
};

my $sftp;
$sftp = Net::SFTP::Foreign->new(
    HOST,
    timeout  => 240,
    user     => USER_NAME,
    password => PASSWORD,
    autodie  => 1,
) or die "Connection failed: " . $sftp->error;

$sftp->setcwd(REMOTE_DIR);
my @files = @{ $sftp->ls };    #Returns a reference to an array of hashes

for my $file (@files) {
    print "Found file $file->{filename}\n";

    $sftp->rget( $file, $file, on_error => sub { print $sftp->error; } );
    print "File - $file transferred\n";

    # Delete Files
    $sftp->rremove( $file, on_error => sub { print $sftp->error; } );
    print "Deleted File -$file\n";
}

When i run the above code, i get the error as below.

Couldn't stat remote link: No such file

But when i go to the remote location, the directories are present.

But when i try without the for loop using the below code, then it is working fine.

$sftp->rget( REMOTE_DIR, LOCAL_DIR, on_error =>
      sub { print $sftp->error; } ) ;

But my requirement is to use a for loop so that i can delete the transfered file as soon as it is transferred. Because deleting separately might cause problems as directories will get added in SFTP frequently and i dont want to delete any folders that have not been transferred.

ls() returns an array of hashrefs. You want to get/remove $file->{filename} , not $file .

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