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

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |