主机无法访问时的Perl ssh错误处理

时间:2012-11-23 11:53:10

标签: perl networking ssh expect

我在perl中使用expect来执行ssh,以下是我的代码snipet。

my $exp = Expect->spawn("ssh renjithp\@192.168.1.12") or die "could not spawn ssh";
my $op = $exp->expect(undef,'renjithp>');
print "*$op*";

如果无法访问主机(目标IP已关闭),我想处理错误,我在印象时会在无法访问IP时遇到错误,但是当我提供错误的IP脚本时,我的目标并未终止,而且持续执行。

处理这种情况的正确方法是什么?

EDITED 我观察到当ssh成功时$ op值为1,而当目标IP未启动时为0。是使用$ op做出决定的正确方法吗?

我还有一个疑问,当目标IP无法访问时,为什么控件出现了预期,我的意思是'$ exp-> expect(undef,'renjithp>');'只有在得到提示后才能返回?

2 个答案:

答案 0 :(得分:2)

如果您需要使用expect模块使用IP地址可达性进行ssh连接,则应首先使用nc测试连接...

my $addr = "192.168.1.12";
if (system("nc -w 1 -z $addr 22")==0) {
    my $exp = Expect->spawn("ssh renjithp\@$addr") or die "could not spawn ssh";
    my $op = $exp->expect(undef,'renjithp>');
    print "*$op*";
} else {
    print "Host $addr is unreachable\n";
}

nc命令是netcat ... nc -z测试TCP端口打开

或者,您可以使用像Net::OpenSSH这样的模块,使错误处理更容易......

use Net::OpenSSH;

my $ssh = Net::OpenSSH->new($host);
$ssh->error and
   die "Couldn't establish SSH connection: ". $ssh->error;

答案 1 :(得分:2)

使用Net :: OpenSSH:

use Net::OpenSSH;

my $ssh = Net::OpenSSH->new($host, timeout => 30);
if ($ssh->error) {
    die "Unable to connect to remote host: " . $ssh->error;
}
my $out = $ssh->capture($cmd);
...