简体   繁体   中英

Perl - Net::SFTP::Foreign

I am trying to write an upload script in Perl , using Net::SFTP::Foreign.

I am having issue with checking if the directory exists, and if it does not, creating it.

Net::SFTP::Foreign seems to just error and close the connection if the directory doesn't exist, and never runs the "else"

You can see the code below, can aanyone see where im going wrong?

sub uploadtoftp
{
use Net::SFTP::Foreign;
use File::Basename;
use warnings;

  my $host=$_[0];
  my $user=$_[1];
  my $pw=$_[2];


   my $home_directory ="/home/testuser";
  my $remote_path=$home_directory."/".$name."/".$destination_dir;



  if (my $ftp = Net::SFTP::Foreign->new($host,
                                   user => $user,
                                   password => $pw,
                                   autodie => 0))
  {

      my $destination_dir_proceed=0;


        $ftp->find("$remote_path", on_error => sub { print "Creating directory\n"; $ftp->mkdir("$remote_path")  });
        print $ftp->error;


        if($ftp->opendir($remote_path)) 
        {
          $destination_dir_proceed=1;
        }


        if($destination_dir_proceed==1) 
        {
        # --- loop through file list and upload all new files
        foreach $filename (split(/ /, $file_list)) 
        {
          $ftp->put($filename,$remote_path.$filename);

        }


        }

      else
      {
        print "cannot reach directory $remote_path\n";
      }


  }




} # end subroutine uploadtoftp()

When you instantiated the Net::SFTP::Foreign object, you created it with autodie => 1 .

Autodie will "promote non-recoverable errors to execptions automatically".

You can remove the autodie line and be OK as long as you're checking for status regularly throughout the script.

If there are places you want to die at, you can use die_on_error after you've made a request

You can use the following logic to create the folder:

$ftp->find("$remote_path", on_error => sub { print "Creating directory\n"; $ftp->mkdir("$remote_path") });

if you do not need print statement:

$ftp->find("$remote_path", on_error => sub { $ftp->mkdir("$remote_path") });

If you need to create all missing folders in the path, this should work (I cannot currently test it, but the idea seems correct).

my $home_directory ="home/testuser";
my $remote_path=$home_directory."/".$name."/".$destination_dir;

my $currentPath = '';
foreach my $directory (split '/', $remote_path) {
    $currentPath = "$currentPath/$directory";
    $ftp->find("$currentPath", on_error => sub { print "Creating directory\n"; $ftp->mkdir("$currentPath") });
}

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