我已经构建了一个脚本,它将ssh
对远程服务器执行某些命令。为了使执行成功,我一直等到END
从命令结果中获取关键字。
因此,在积极的测试用例场景中,这可以正常工作。
...
foreach my $ip( @list_of_ips ){
chomp($ip);
eval {
$ssh = SSH_Connection( $ip, $user, $passwd );
print "Connection is Success to $ip\n" if($ssh);
};
$command_to_execute = "<forming a command which needs be execute in remote server>";
print "$command_to_execute\n";
my $str = 'END';
eval{
$ssh->send("$command_to_execute; echo $str");
};
$ssh->waitfor($str, undef);
last if($ssh);
}
...
...
sub SSH_Connection {
my ( $host, $user, $passwd ) = @_;
my $ssh = Net::SSH::Expect->new ( host => $host, user => $user, password => $passwd, raw_pty => 1, no_terminal => 0 );
my $login_output;
my $handledie = eval {
$login_output = $ssh->login();
};
if ( $@ ) {
if ($@ =~ m/SSHConnectionError/i ) {
print "SSH Connection Error\n";
next;
} elsif ( $@ =~ m/SSHProcessError/ix ) {
print "SSH Process Error\n";
next;
} elsif ( $@ =~ m/SSHConnectionAborted/ix ) {
print "SSH Connection Aborted\n";
next;
} else {
print "SSH Unknown Error: $@\n";
next;
}
}
if ($login_output !~ /Last login/) {
die "Login has failed.";
} else {
return $ssh;
}
print "SSH to ip failed\n";
}
但是当连接到远程主机成功并且命令执行失败时,会出现以下错误并从脚本中退出。
SSHProcessError The ssh process was terminated at ...script.pl line 47
我们$ssh->waitfor($str, undef);
在第 47 行。
我们如何解决这个问题?TIA。