tags:

views:

529

answers:

5

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 privileges to install Net::SSH which would make my task very easy. Please provide me a solution for this. I tried using backticks but I am not able to store the output on the machine from which my script runs.

A: 

If you have ssh host keys setup you can simply run the ssh system command and then specify the command to run on the machine after that. For example:

`ssh [email protected] id`

You should be able to chomp/store that output.

malonso
+5  A: 

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"
Chas. Owens
A: 

Assuming that you're in an environment like me where you can't add additional modules and you can't create an Identity file, then you can use this script as a starting point.

If you can set up ssh keys then simply use the backticks command already posted, although you might need the -i option

#!/usr/bin/perl
use warnings;
use strict;
use Expect;
use Data::Dumper;

my $user = 'user';
my $pw = 'password';
my $host = 'host';
my $cmd = 'id';

my $exp = new Expect;
$exp->log_file("SSHLOGFILE.txt");
$exp->log_stdout(0);
$exp->raw_pty(1);


my $cli = "/usr/bin/ssh $user\@$host -o StrictHostKeyChecking=no -q $cmd";

$exp->spawn($cli) or die "Cannot spawn $cli: $!\n";

$exp->expect(5,
 [ qr /ssword:*/ => sub { my $exph = shift;
                          $exph->send("$pw\n");
                          exp_continue; }] );

my $read = $exp->exp_before();
chomp $read;
print Dumper($read);

$exp->soft_close();
John Mikkola
+1  A: 

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 Brain 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;
Space
@salman: Any update on this?
Space
A: 

If you're using backticks try this:

my @output = `ssh [email protected] "which perl"`;

print "output: @output";

This is only useful if you have a publickey that the above command won't prompt for password.

Ricky