TheOne745665
TheOne745665

Reputation: 437

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()

Upvotes: 0

Views: 994

Answers (2)

Andrey
Andrey

Reputation: 1818

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") });
}

Upvotes: 0

Trenton Trama
Trenton Trama

Reputation: 4930

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

Upvotes: 2

Related Questions