siddhanta has asked for the wisdom of the Perl Monks concerning the following question:

Hi, This is my first Perl Script.

Am trying to scp file from 1 server to another. Script is working fine. But I need to put some error handling logic that I usually use to do with shell script. 1) Redirect output of command to a file 2) Status of the previous command

Can you please help me to achieve above logic. I tried looking in google but did not find/understand the solution.

#!/usr/bin/perl use strict; use Net::SCP::Expect; my $user = 'user1'; my $host = 'host1'; my $pass = 'pass1'; my $src_file = "/home/Script_Name.txt"; my $dst_path = "/home/"; my $s = Net::SCP::Expect->new; $s->login($user, $pass); $s->scp("$host:$src_path",$dst_path);

Replies are listed 'Best First'.
Re: Net::SCP::Expect Error Handling
by salva (Canon) on Jan 29, 2016 at 08:21 UTC
    Net::SCP::Expect documentation says nothing about error handling, but looking at the source code, you would see that its method scp throws and exception when authentication fails in any way or when the slave scp process exists with a non-zero return code.

    The Expect object used internally to handle interaction with the slave scp process is not exposed. I can't see a way to retrieve the output.

    Anyway, let my present you Net::OpenSSH which is able to do what you are asking for:

    use Net::OpenSSH; my $ssh = Net::OpenSSH->new($host, user => $user, password => $pass); unless ($ssh->scp_get({ stdout_file => './scp-capture', stderr_to_stdout => 1 }, $src_path, $dst_path)) { say "SCP failed: " . $ssh->error; ... }

    update: oops! s/stdin/stdout/g !!! There was also a missing parenthesis.

      Thanks. Can you please explain the code. especially stdin functionality.

      In the mean time , i have used the eval function to catch the error

      #!/usr/bin/perl use Net::SCP::Expect; my $user = 'user1'; my $pass = 'pass1'; my $host = 'host1'; my $src_path = "/home/sid.txt"; my $dst_path = "/home/datprd/"; my $s = Net::SCP::Expect->new; $s->login($user, $pass); eval{ $s->scp("$host:$src_path",$dst_path);}; print $@;
        Under the hood the scp methods in Net::OpenSSH call the scp command.

        The option stdout_file indicates a file name where to redirect the output from the command. stderr_to_stdout indicates that stderr should be send to the same place as stdout. That combination is equivalent to the shell >./scp-capture 2>&1.