【问题标题】:Error handling in Net::Openssh (host ,async =>1) optionNet::Openssh (host ,async =>1) 选项中的错误处理
【发布时间】:2013-02-06 02:49:17
【问题描述】:

我正在使用 Openssh 模块通过 (async => 1) 选项连接到主机。 如何为那些无法连接的主机捕获连接错误。我不希望错误出现在终端中,而是存储在数据结构中,因为我想最终将所有数据格式化为 cgi脚本。当我运行脚本时,有连接问题的主机在终端中抛出错误。代码进一步执行并尝试在断开连接的主机上运行命令。我想隔离断开连接的主机。

my (%ssh, %ls);        #Code copied from CPAN Net::OpenSSH
my @hosts = qw(host1 host2 host3 host4 );
 # multiple connections are stablished in parallel:
  for my $host (@hosts) {
  $ssh{$host} = Net::OpenSSH->new($host, async => 1); 
  $ssh{$host}->error and die "no remote connection "; <--- doesn't work here! :-(  
  }
# then to run some command in all the hosts (sequentially):
 for my $host (@hosts) {
 $ssh{$host}->system('ls /');
}

$ssh{$host}->error and die "no remote connection doesn't work"。

任何帮助将不胜感激。 谢谢

【问题讨论】:

标签: perl perl-module


【解决方案1】:

您运行异步连接。所以程序继续工作并且在连接建立时不要等待。 在 newasync 选项之后,您尝试检查错误,但它没有被定义,因为连接正在进行中并且没有关于错误的信息。

据我了解,您需要在第一个循环后等待,直到连接过程得到结果。

尝试使用 ->wait_for_master(0);

如果给定了一个假值,它将完成连接过程并等待多路复用套接字可用。

连接成功后返回真值。如果连接过程失败或尚未完成,则返回 False(然后,可以使用“错误”方法来区分这两种情况)。

for my $host (@hosts) {
    $ssh{$host} = Net::OpenSSH->new($host, async => 1); 
}

for my $host (@hosts) {
    unless ($ssh{$host}->wait_for_master(0)) {
        # check $ssh{$host}->error  here. For example delete $ssh{$host}
    }
}

# Do work here

我不检查此代码。

PS:对不起我的英语。希望对你有帮助。

【讨论】:

  • wait_for_master(0) 不起作用。它中止主 ssh 连接!
  • @Alex:wait_for_master 应该可以工作。如果失败,请通过不带异步标志的连接来检查连接参数是否正确。
猜你喜欢
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 2016-11-05
  • 2016-08-04
相关资源
最近更新 更多