Perl Net::Telnet 远程登录执行命令的问题
我在Shell中调用了一段perl程序,登陆到远程主机执行命令。在多次重复的执行后,发现远端的主机IP协议栈崩溃了,再也ping
不通了。远端主机是ulinux系统。如果我每次手动登陆远程主机执行命令然后退出,将不会出现这种情况。我想请教一下下面的这
段代码是否正确的关掉了与远端主机之间的会话。还有如果我用Expect写一段交互程序的话,最后执行exit。会不会不出现类似
情况?
多谢!
sub telnet_client
{
my $t;
my @lines;
my $ip_address = shift;
my $user = shift;
my $password = shift;
my $mode="return";
my $rv;
my $command;
my $num_retries = shift;
my $logged_in = 0;
my $retry_cnt = 0;
my $session_open = 0;
my $timeout;
my $cmdtimeout = shift;
$timeout = $cmdtimeout if ($cmdtimeout > 0);
$t = new Net::Telnet (Timeout => $timeout);
$t->errmode($mode);
while ($logged_in == 0)
{
if ($session_open == 0) {
$rv = $t->open($ip_address);
if (!(defined $rv))
{
print "telnet_client: ".$t->errmsg, "\n";
return 1;
}
$session_open = 1;
}
$rv = $t->login (Name => $user,
Password => $password,
Timeout => 10);
if (! defined $rv)
{
if ($t->errmsg !~ /timed-out/) {
print "telnet_client: ".$t->errmsg, "\n";
return 1;
}
elsif ($password ne ""
{
print "telnet_client: ".$t->errmsg, "\n";
if ($retry_cnt < $num_retries)
{
$retry_cnt = $retry_cnt + 1;
$t->close();
$session_open = 0;
sleep (15);
next;
}
else
{
print "Log in failed after ", $retry_cnt, " retries !\n";
$t->close();
$session_open = 0;
return 1;
}
}
}
($prematch, $match) = $t->waitfor (Match => '/# *$/', Timeout => 5);
if ($match !~ /# *$/)
{
$t->print ("";
($prematch, $match) = $t->waitfor (Match => '/# *$/', Timeout => 5);
}
if ($match =~ /# *$/)
{
$logged_in = 1;
}
else
{
print "telnet_client: ".$t->errmsg, "(shell prompt)", "\n";
if ($retry_cnt < $num_retries)
{
$retry_cnt = $retry_cnt + 1;
$t->close();
$session_open = 0;
sleep (15);
}
else
{
print "Log in failed after ", $retry_cnt, " retries !\n";
$t->close();
$session_open = 0;
return 1;
}
}
}
$command = shift;
while (defined $command)
{
@lines = $t->cmd($command);
if (@lines == ())
{
print "telnet_client: ".$t->errmsg, "\n";
$t->close();
$session_open = 0;
return 1;
}
else
{
pop (@lines);
print @lines;
}
$command = shift;
}
# Get the return code of the command
@lines = $t->cmd("echo \$?";
$lastLine = @lines[$#lines-1];
$lastLine =~ s/\n$//;
@lines = $t->cmd("exit";
$t->close();
$session_open = 0;
return $lastLine;
}