简体   繁体   English

在Perl中使用sftp外部模块传输目录

[英]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. 我正在尝试将所有目录及其内容从sftp传输到unix服务器,并从SFTP服务器删除所有已传输的文件。 I am using rget method in SFTP::Foreign module for this purpose. 为此,我在SFTP :: Foreign模块中使用rget方法。 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. 但是,当我尝试不使用以下代码进行for循环时,则工作正常。

$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. 但是我的要求是使用for循环,这样我就可以在传输文件后立即删除它。 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. 因为单独删除可能会导致问题,因为目录将频繁地添加到SFTP中,因此我不想删除尚未传输的任何文件夹。

ls() returns an array of hashrefs. ls()返回一个哈希引用数组。 You want to get/remove $file->{filename} , not $file . 您要获取/删除$file->{filename} ,而不是$file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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