【问题标题】:Getting exit status of command executed using exec of Net::SSH::Expect获取使用 Net::SSH::Expect 的 exec 执行的命令的退出状态
【发布时间】:2014-05-12 02:23:36
【问题描述】:

我正在运行以下脚本:

#!/usr/local/bin/perl -w

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


my $ssh = Net::SSH::Expect->new(host=>"xxx.xxx.xxx.xxx",password=>"xxxxxxx", user=>"root" ,timeout=>3  );

$ssh->login();
$ssh->exec("stty -echo");

print "Connection Established\n";

my ($out) = $ssh->exec("rpm -ivh xxx");
print "\n\nOUTPUT: $out\n";


#$ssh->send("echo $?");
($out) = ($ssh->get_expect())->exitstatus();

print "\n\nEXIT STATUS: $out\n";

运行这个,我无法获得我执行的“rpm -ivh ...”命令的退出状态。

我是 Perl 新手,请帮帮我。

【问题讨论】:

  • 为什么要在 ($out) 周围加上括号?文档没有这些。 (metacpan.org/release/Net-SSH-Expect) 此外,如果您有“使用警告”,您可以删除第一行中的 -w 标志。
  • @davewood。确实,您应该尝试$out = $ssh->exec("rpm -ivh xxx"); ...但这不会解决您对$? 的渴望,也不会解决远程提示和/或prompt_command 的潜在问题。

标签: linux perl ssh expect


【解决方案1】:

这与$? 行为的预期一致。

Net::SSH::Expect 模块只不过是 Expect 处理远程命令执行的方式:您只能依赖命令输出,而不是提供给远程 shell 的底层退出代码值。 p>

您可以:

  • 修改远程执行的命令,以某种方式显示/返回与命令退出状态相关的一些字符串: 例如:rpm -ivh xxx && echo OK),

  • 使用较少面向文本输出的 SSH 模块,例如 Net::OpenSSH。它是一个功能很好的模块,接近 SSH 协议并积极维护。

    • 来自 Net::OpenSSH 文档:

      $ssh->system(\%opts, @cmd)

      在远程机器上运行命令@cmd。成功时返回 true,否则返回 undef

      错误状态设置为 OSSH_SLAVE_CMD_FAILED 当远程命令以非零代码退出时(该代码可从$?获得,请参阅perlvar中的“$?”)。

    • 使用 Net::OpenSSH

      #!/usr/bin/env perl
      use strict;
      use warnings;
      use Net::OpenSSH;
      my $ssh = Net::OpenSSH->new( "xxx.xxx.xxx.xxx",
                                   user    => "root" ,
                                   passwd  => "xxxxxxx", 
                                   timeout => 3, 
                                 );
      
      if ($ssh) {
           print "Connection Established\n";
      
           my $out = $ssh->capture("rpm -ivh xxx");
           print "\n\nOUTPUT: $out\n";
           print "\n\nEXIT STATUS: $?\n";
      }
      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-24
    • 2013-03-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多