Reputation: 407
I use expect in perl to do ssh, following is my code 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*";
I wanted to handle the error if the host is not reachable (destination IP is down), I was in a impression die will hit when the ip is not reachable, but when i give a wrong IP script is not terminating and it continuous execution.
what is the right way to handle this scenario?
EDITED I am observing $op value is 1 when the ssh is succesfull, and 0 when the destination IP is not up. is it right way to use $op to take a decision?
I have one more doubt, when the destination IP is not reachable why the control coming out of expect,i mean '$exp->expect(undef,'renjithp>');' should return only after its getting the prompt right?
Upvotes: 2
Views: 2590
Reputation: 43077
If you need to make the ssh connection contingent on IP address reachability with the expect module, you should test connectivity with a nc
first...
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";
}
The nc
command is netcat
... nc -z
tests for TCP port open
Alternatively, you could use a module like Net::OpenSSH
that makes error handling a bit easier...
use Net::OpenSSH;
my $ssh = Net::OpenSSH->new($host);
$ssh->error and
die "Couldn't establish SSH connection: ". $ssh->error;
Upvotes: 2
Reputation: 10234
use 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);
...
Upvotes: 2