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.
22 Answers
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-perlAnd finally —assuming you call it script.pl— call it like so:
perl -MNet::OpenSSH::Compat=Net::SSH2 script.pl 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:
- Do it cleanly as described in Oli's answer.
- Set up passwordless, key-based ssh authentication.
Use
sshpassFirst, install it from the repositories:
sudo apt-get install sshpassThen run this:
perl -e '$r=`sshpass -p "password" ssh user\@host hostname`; print "Remote host:$r"'