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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With