0

As clearly explained in the question, kindly give me an option to ssh to a machine using perl script, run a few script lines there, and return the output to the source machine.

Found out a few docs online on this, but nothing seems to be informative/clear.

Please help.

2 Answers2

5

I agree that the current examples look helpful but don't always work! My previous examples are included in that. I'm not a Perl expert at all but I've cobbled the following together and it works for me:

#!/usr/bin/perl -w
use strict;

use Net::SSH2;

my $ssh2 = Net::SSH2->new();
$ssh2->connect('tank') or die $!;
my $auth = $ssh2->auth_publickey(
    'oli',
    '/home/oli/.ssh/id_rsa'
);

my $chan2 = $ssh2->channel();
$chan2->blocking(1);

# This is where we send the command and read the response
$chan2->exec("uname -a\n");
print "$_" while <$chan2>;

$chan2->close;

Obviously you'll want to change the hostname, username and location of your RSA/DSA/etc key. Additionally, you'll need the compat library to make this work well on Ubuntu:

sudo apt-get install libnet-openssh-compat-perl

And finally —assuming you call it script.pl— call it like so:

perl -MNet::OpenSSH::Compat=Net::SSH2 script.pl
Oli
  • 299,380
2

You could always just run a system call from within your shell script. As long as you can ssh from the shell, you don't need to install anything:

perl -e '$r=`ssh user\@host hostname`; print "Remote host:$r"'

If you need to run this automatically, you have a few options:

  1. Do it cleanly as described in Oli's answer.
  2. Set up passwordless, key-based ssh authentication.
  3. Use sshpass

    First, install it from the repositories:

    sudo apt-get install sshpass
    

    Then run this:

    perl -e '$r=`sshpass -p "password" ssh user\@host hostname`; print "Remote host:$r"'
    
terdon
  • 104,119