从脚本中,在远程服务器上运行脚本并获取其输出

时间:2017-08-08 11:17:32

标签: perl ssh

我正在执行一个Perl脚本。我必须SSH到远程服务器并执行python脚本。下面是我在perl脚本中执行的代码行。我知道有几个选项,如反引号和系统命令来执行python脚本,但我有远程服务器中的脚本,我不能使用系统或反引号命令,因为它不是本地机器。我想要在运行时通过SSH执行命令的输出。

   my $ssh = new Net::SSH::Expect();
    $ssh->login_username($server_login);
    $ssh->server($server_name);
    $ssh->login();
    my $home_directory= $ssh->pwd;

my $command=qq(/home/feroz/MyScript.py $ARG0 $ARG1 $ARG2 $ARG3 1)
    print "\n-------- BEGIN SCRIPT OUTPUT ----------\n";
    $ssh->exec($command)){

    print "\n -------- END SCRIPT OUTPUT ----------";

1 个答案:

答案 0 :(得分:2)

请参阅Net::SSH::Expect文档。你没有正确使用它

use warnings;
use strict;
use Net::SSH::Expect;

my $ssh = Net::SSH::Expect->new (
    host     => 'host name', 
    user     => 'user name', 
    password => 'password', 
    raw_pty  => 1
);

my $greeting = $ssh->login();  # or $ssh->run_ssh(), if without password
print $greeting;

# Disable terminal translations and echo on the SSH server
$ssh->exec("stty raw -echo");

my $cmd = q( ... );

my $cmd_output = $ssh->exec($cmd);

print $cmd_output, "\n";

exec方法是获取命令输出的方法之一。其他一些是read_linepeekeat,还有其他方法可以与命令进行交互。

请添加支票以查看登录是否有效。

这可以完成很多,而且涉及复杂性。请阅读文档。

相关问题