gpt4 book ai didi

linux - 使用 Net::SSH::Expect 的 exec 获取执行命令的退出状态

转载 作者:太空狗 更新时间:2023-10-29 12:16:33 28 4
gpt4 key购买 nike

我正在运行以下脚本:

#!/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 的新手,请帮我解决这个问题。

最佳答案

这符合 $? 行为的预期。

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

您可以:

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

  • 使用像 Net::OpenSSH 这样较少文本输出的 SSH 模块。它是一个具有良好特性的模块,接近 SSH 协议(protocol)并得到积极维护。

    • 来自 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";
      }

关于linux - 使用 Net::SSH::Expect 的 exec 获取执行命令的退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22783727/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com