Bootstrap FreeKB - Perl (Scripting) - Public key authentication with Net::SSH::Perl
Perl (Scripting) - Public key authentication with Net::SSH::Perl

Updated:   |  Perl (Scripting) articles

If you are not familiar with the Net::SSH:Perl module, check out Getting Started with Net::SSH:Perl.

Here is an example of how you would SSH onto a target system using a key pair instead of a password. This assumes you are already setup passwordless SSH authentication between the system that you are running the Perl script from and the target system.

#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH::Perl;

my @private_keys = ("/home/john.doe/.ssh/id_rsa");
my $ssh = Net::SSH::Perl->new('server1.example.com', debug=>1, identity_files=>\@private_keys);
$ssh->login('john.doe');

 

Better yet, the eval function can be used to determine if the SSH connection to the host is successful, or if there is some issue.

#!/usr/bin/perl
use strict;
use warnings;
use Net::SSH::Perl;

my @private_keys = ("/home/john.doe/.ssh/id_rsa");

eval {
  my $ssh = Net::SSH::Perl->new('server1.example.com', debug=>1, identity_files=>\@private_keys);
  $ssh->login('john.doe');
};

chomp $@;

if ($@) {
  print "Failed to login to server1.example.com. eval found the following issue: $@ \n";
  exit 1;
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 865734 in the box below so that we can be sure you are a human.