Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ssh inside a Perl script?

Tags:

ssh

perl

I want to SSH to a server and execute a simple command like "id" and get the output of it and store it to a file on my primary server. I do not have privileges to install Net::SSH which would make my task very easy. Please provide me a solution for this. I tried using back-ticks but I am not able to store the output on the machine from which my script runs.

like image 617
Salman Avatar asked May 17 '10 11:05

Salman


People also ask

How do I SSH into a Perl script?

Net::SSH::Perl->new($host, %params) To set up a new connection, call the new method, which connects to $host and returns a Net::SSH::Perl object. The protocol you wish to use for the connection: should be either 2 , 1 , '1,2' or '2,1' .


2 Answers

The best way to run commands remotely using SSH is

$ ssh user@host "command" > output.file

You can use this either in bash or in perl. However, If you want to use perl you can install the perl modules in your local directory path as suggested by brian in his comment or from Perl FAQ at "How do I keep my own module/library directory?". Instead of using Net::SSH I would suggest to use Net::SSH::Perl with the below example.

#!/usr/bin/perl -w
use strict;
use lib qw("/path/to/module/");

use Net::SSH::Perl;

my $hostname = "hostname";
my $username = "username";
my $password = "password";

my $cmd = shift;

my $ssh = Net::SSH::Perl->new("$hostname", debug=>0);
$ssh->login("$username","$password");
my ($stdout,$stderr,$exit) = $ssh->cmd("$cmd");
print $stdout;
like image 95
Space Avatar answered Sep 20 '22 01:09

Space


You can always install modules locally, and that is the method you should look into; however, you should be able to get away with

#!/usr/bin/perl

use strict;
use warnings;

my $id = qx/ssh remotehost id 2>&1/;

chomp $id;

print "id is [$id]\n"
like image 43
Chas. Owens Avatar answered Sep 19 '22 01:09

Chas. Owens