Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Net::SSH::Perl using forwarded SSH key

Tags:

ssh

perl

I am trying to write a perl script using Net::SSH::Perl

Its quite simple at the moment as I just want to perform an ls in a directory over ssh.

#!/usr/bin/perl

use Net::SSH::Perl;

@KEYFILE = ("/user/.ssh/id_rsa");
$ssh = Net::SSH::Perl->new($host, debug=>1, identity_files=>\@KEYFILE)

my $host = "hostname";
my $user = "user";

#-- set up a new connection
my $ssh = Net::SSH::Perl->new($host, debug=>1, identity_files=>\@KEYFILE)
#-- authenticate
$ssh->login($user);
#-- execute the command
my($stdout, $stderr, $exit) = $ssh->cmd("ls -l /home/user/");

This works, but the only problem is, I need to jump through a bastion server to run the commands. I forward my private key to the bastion, but the bit I am stuck on is how to use the forwarded key in perl, rather than using a key which would have to be on the server.

Is this possible?

Thanks

like image 641
Tony Avatar asked Apr 12 '13 10:04

Tony


2 Answers

You have to enable agent forwarding when connecting to the bastion server:

my $ssh = Net::SSH::Perl->new(
    $host,
    debug          => 1,
    identity_files => \@KEYFILE,
    options        => [
        'ForwardAgent yes',
    ],
);

For other ssh Perl modules and their pros and cons see Net::OpenSSH vs Net::SSH:: modules.

like image 82
Alexander Hartmaier Avatar answered Nov 14 '22 16:11

Alexander Hartmaier


You can pass in the file contents as a scalar reference.

my $ssh = Net::SSH::Perl->new($host, identity_files => [ \$file_contents ]);

However if you're going to ssh through a bastion server, then forwarding the SSH agent is the best way to do this (as abraxxa has shown above).

like image 2
Uncle Arnie Avatar answered Nov 14 '22 16:11

Uncle Arnie