Thursday, November 6, 2008

Getting output from a remote program using PERL + SSH

Basically what I was trying to do is establish an ssh connection, get a port that is open on that server, and return it back to the connecting server. What you will need is really two portions of a code, first off, a program on the server that returns the port, it can be as simple as print "PORT=21"; then secondly you need the code shown below that calls the remote program above:

my @remote_stdout = split("\n", `ssh $user\@$host '"<cmd>"'`);
if($? != 0) {
warn ":ERROR: could not establish ssh connection with '$host' host";
} else {
my $last_stdout_line = pop @remote_stdout;
my $remote_command_result;
if(defined $last_stdout_line and ($last_stdout_line =~ m/^PORT=(\d+)$/)) {
$remote_command_result = $1;
}
if(defined $remote_command_result) {
warn ":Port Found: $remote_command_result";
} else {
warn ":ERROR: no results";
}
}

No comments: