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
or, assuming host keys are present and you want to do something with the command ouput ...
open(SSH,"/usr/bin/ssh you\@server ps aux |") or die "$!\n";
while (<SSH>) {
# do stuff with $_
}
close SSH;
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();
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 user@remoteserver.domain.com id`
You should be able to chomp/store that output.