running bash command using SSH in PERL

2019-07-24 22:21发布

问题:

Please be patient. I'm very new to perl. I'm passing a HTML variable from html form to a PERL/CGI script. Pls see the following

#!/usr/bin/perl

use strict; use warnings;
use CGI::Carp; # send errors to the browser, not to the logfile
use CGI;
my $cgi = CGI->new(); # create new CGI object
my $name = $cgi->param('servername');
print $cgi->header('text/html');
print "Server name is /n, $servername";
#system("/var/www/cgi-bin/localbashscript $servername");
#system("ssh $servername "remotebashscript" > localfile or display back to html );

Basically from the HTML form, I need to pass the server name. I tried using the system command to pass on the servername to "localbashscript" that runs my ssh command. But, I cannot get it to work. It was suggested that I do the SSH in PERL, but I have no idea how to do it.

In short, I have to call a bash script (remotebashscript) on the remote server ( $servername) and display the content back to the html or at least pipe it to a local file. The first thing I need to do before running the remotebashscript is to set my environment variables. This is how I would do it in bash. I set my env variable by sourcing the .profile and then I execute the remotebashscript and redirect it to a local file.

  ssh $servername ". ~/.profile;remotebashscript" > localfile

I have no idea how to achieve the same thing using perl and seek your help. I tried below and did not work

 system("ssh $servername ". ~/.profile; remotebashscript" ");

Thanking you in advance

回答1:

Please: Never, never, never use user input in a call to system, without at least trying to sanitize them! It is a terrible mistake to assume that the user won't break your system by entering strings that can somehow escape what you're trying to do and do something else. In this case, something like 192.168.0.1 rm -rf / would be sufficient to delete all files from your ssh server. Please heed the standard way of doing things, which is never using user input in a executed command.

There's plenty of modules, and even a standard one, Net::SSH, which can do SSH for you.



回答2:

As Jens suggested you should use Net::SSH, that'll make your task easy and reliable.

Sample:

#always use the below in your Perl script
use strict;
use warnings;
#load the Net::SSH module and import sshopen2 from it
use Net::SSH qw(sshopen2); 
#type credentitals and the command you want to execute (this would be your bash script)
my $user = "username";
my $host = "hostname";
my $cmd = "command";
#use sshopen2 to run your command 
sshopen2("$user\@$host", *READER, *WRITER, "$cmd") || die "ssh: $!";
#read the result 
while (<READER>) { #loop through line by line of result
    chomp(); #delete \n (new line) from each line
    print "$_\n"; #print the line from result
}     
#close the handles
close(READER);
close(WRITER);


标签: html bash perl ssh