Julien
Julien

Reputation: 5779

Net::SCP / Net::SCP::Expect - how to deal with password vs key authentication

I have a script that works on different clients, and need to SCP files to different hosts. Depending on the combination of client & server, I may need to use password authentication or public key authentication. I cannot really know in advance which one to use.

There are 2 CPAN libraries for SCP that I use:

The problem is that neither library works for both authentications, and I don't know which one to use in advance. Do you know of any way to work with both authentication schemes?

Upvotes: 3

Views: 4458

Answers (2)

salva
salva

Reputation: 10244

try Net::OpenSSH

Upvotes: 0

Greg Bacon
Greg Bacon

Reputation: 139531

Try one and fail over to the other:

#! /usr/bin/perl

use warnings;
use strict;

use Net::SCP qw/ scp /;
use Net::SCP::Expect;

my @hosts = qw/ host1 host2 host3 /;
my $user  = "YOUR-USERNAME-HERE";
my $pass  = "PASSWORD-GOES-HERE";
my $file  = "file-to-copy";

foreach my $host (@hosts) {
  my $dest = "$host:$file"; 

  my $scp = Net::SCP->new($host, $user);
  unless ($scp->scp($file => $dest)) {
    my $scpe = Net::SCP::Expect->new;
    $scpe->login($user, $pass);

    local $@;
    eval { $scpe->scp($file => $dest) };
    next unless $@;

    warn "$0: scp $file $dest failed:\n" .
         "Public key auth:\n" .
         "    $scp->{errstr}\n" .
         "Password auth:\n" .
         "    $@\n";
  }
}

Upvotes: 5

Related Questions