Transfer file from Remote machine to local machine using Net::OpenSSH

Viewed 99

I have built a script which should get a file from remote machine to local machine.

#!/usr/bin/perl

use strict;
use warnings;

use Net::OpenSSH;
use Data::Dumper;

my $local_dir = "/LOCAL/DIR/LOCATION/"
print "[LOCAL DIR]-> $local_dir\n";

my $remote_dir = "/REMOTE/DIR/LOCATION/";
print "[REMOTE DIR]-> $remote_dir\n";

my ($host, $user, $password) = ("remote.machine.ip.address", "userid", "password");

my $ssh = Net::OpenSSH->new($host,
                            user => $user,
                            password => $passwd,
                            master_opts => [-o => "StrictHostKeyChecking=no"]
);
$ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;

my @file = $ssh->capture("cd $remote_dir && ls -1tr | grep Report | tail -1");
print "[FILE]:\n".Dumper(\@file);

$ssh->scp_get({glob => 1}, "$remote_dir$file[0]", $local_dir)
        or die "scp failed: " . $ssh->error;

undef $ssh;

In the above code its able to print the Dumper value for @file but unable to get the file in local system.

Here is the error it throws at the end:

[FILE]:
$VAR1 = [
          'Report_Managable_20200705.csv
'
        ];
scp: /REMOTE/DIR/LOCATION/Report_Managable_20200705.csv
protocol error: expected control record
scp failed: scp failed: child exited with code 1 at file_get_test.pl line 22.

Can anybody help me to fix this issue. TIA.

1 Answers

The list returned by $ssh->capture() has new lines at the end of each item. Try use chomp @file to remove the newlines.

Related