【问题标题】:running bash command using SSH in PERL在 PERL 中使用 SSH 运行 bash 命令
【发布时间】:2015-01-12 16:38:05
【问题描述】:

请耐心等待。我对 perl 很陌生。我将 HTML 变量从 html 表单传递到 PERL/CGI 脚本。请看以下内容

#!/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 );

基本上从 HTML 表单中,我需要传递服务器名称。 我尝试使用系统命令将服务器名传递给运行我的 ssh 命令的“localbashscript”。但是,我无法让它工作。有人建议我在 PERL 中进行 SSH,但我不知道该怎么做。

简而言之,我必须在远程服务器 ($servername) 上调用 bash 脚本 (remotebashscript) 并将内容显示回 html 或至少将其通过管道传输到本地文件。在运行 remotebashscript 之前我需要做的第一件事是设置我的环境变量。这就是我在 bash 中的做法。我通过获取 .profile 来设置我的环境变量,然后执行 remotebashscript 并将其重定向到本地文件。

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

我不知道如何使用 perl 实现相同的目标并寻求您的帮助。我在下面尝试过,但没有成功

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

提前谢谢你

【问题讨论】:

  • 为什么不使用Net::SSH
  • 谢谢,我会调查的
  • 因为您为$name 分配了一个值,然后尝试使用来自$servername 的值?

标签: html bash perl ssh


【解决方案1】:

请:永远,永远,永远不要在调用系统时使用用户输入,至少要尝试清理它们!假设用户不会通过输入可以以某种方式逃避您正在尝试做的事情并做其他事情的字符串来破坏您的系统,这是一个可怕的错误。在这种情况下,192.168.0.1 rm -rf / 之类的内容就足以从您的 ssh 服务器中删除所有文件。请注意标准的做事方式,在执行的命令中绝不使用用户输入。

有很多模块,甚至还有一个标准模块,Net::SSH,它可以为你做 SSH。

【讨论】:

  • 没有理由对正确答案投反对票,并提供有关使用用户输入而不对其进行清理的危险的正确反馈。
  • 这不是一个很好的方式来回答一个显然刚刚开始 Perl 的人提出的问题,他要求非常耐心......然后开始对他大喊大叫......好像他刚刚犯了编程中最大的犯罪。对你的同行程序员这样说你的答案是可以的,但对于初学者来说就不行。
  • @vanHoesel 好吧,你说得对;我会改变措辞,但在我谦逊的眼里,他确实犯下了编程中最严重的罪行之一,这不是在 CGI 中清理用户输入;这确实是每本关于 CGI、Perl 的书,每一位导师和每一位帮助你编写应用程序的朋友都应该告诉你的第一件事。
【解决方案2】:

正如 Jens 建议的那样,您应该使用 Net::SSH,这将使您的任务变得轻松可靠。

示例:

#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);

【讨论】:

  • Thx 正如我所提到的,我是 PERL 的新手。所以我不理解你的例子。我正在尝试将您的示例与我必须做的事情联系起来。所以我必须逐行计算你的例子。这可能需要我一段时间。谢谢你的回复
  • 我在代码中添加了 cmets,以便您了解发生了什么。
猜你喜欢
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 2011-08-26
  • 2013-10-03
  • 2016-11-15
  • 2016-11-09
相关资源
最近更新 更多