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.
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' .
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;
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"
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