Wednesday, June 24, 2015

Perl SSH by example

# Module INSTALLATION
In windows command prompt, to install Net::SSH::Any Perl module (Strawberry Perl)
perl -MCPAN -e "install Net::SSH::Any"


# How to create SSH perl script, pass through single command and get the output:

Still supported example:
http://stackoverflow.com/questions/13457178/perlnetssh2-how-to-keep-the-ssh-connection-while-executing-remote-command

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

use Net::SSH::Any;

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

my $cmd = "@ARGV";

my $ssh = Net::SSH::Any->new($hostname, user => $username, password => $password);
$ssh->error and die $ssh->error;

my $output = $ssh->capture($cmd);
print $output."\n\n";

exit 1;

Old - might not able to get the full perl module installed as it has no longer supported 
http://stackoverflow.com/questions/2848725/how-can-i-ssh-inside-a-perl-script
http://www.perlhowto.com/execute_commands_on_remote_machines_using_ssh

$ ssh user@host "command" > output.file
#!/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;





No comments: