Perl telnet不会等待上一个命令的结束。在文件infile.log中,我看到命令my @ config = $ telnet-> cmd ("sh run");
的继续,但脚本已经开始运行命令print ("Format configuration", $ _, "\ n");
。结果,我得到一个空数组@config。
foreach (@linksys_sps){
print ("Connecting to ",$_,"\n");
my $telnet = new Net::Telnet ( Timeout=>10,Errmode=>'return',Input_Log => "infile.log");
$telnet->open($_);
if ($telnet->errmsg){
print "Can't connect to " . $_ . " Error: " . $telnet->errmsg . "\n";
} else {
$telnet->max_buffer_length(5 * 1024 * 1024);
$telnet->waitfor('/User Name:$/i');
$telnet->print('admin');
$telnet->waitfor('/Password:$/i');
$telnet->print('password');
print ("Set Terminal Variable ",$_,"\n");
$telnet->cmd("terminal datadump");
print ("Create file ",$_,"\n");
my $file = sprintf($folder."/".$_);
print ("Create file ",$file,"\n");
system "touch $file";
system "chown nobody $file";
print ("Read configuration ",$_,"\n");
my @config = $telnet->cmd("sh run");
print ("Write configuration ",$_," to file ",$file,"\n");
open my $fh, "> $file" or die "Can't open $file : $!";
foreach (@config) {
print $fh "$_"; # Print each entry in our array to the file
}
close $fh;
print ("Set Terminal Variable ",$_,"\n");
$telnet->cmd("no terminal datadump");
$telnet->cmd("exit");
}
}
如何解决?
答案 0 :(得分:0)
来自the docs:
方法login()和cmd()使用对象中的提示设置 确定登录或远程命令何时完成。那些方法 如果没有正确设置提示,则会因超时而失败。
换句话说,您需要在创建$telnet
对象时添加prompt参数:
my $switch_name = 's-east';
my $telnet = new Net::Telnet (
Timeout=>10,
Errmode=>'return',
Input_Log => "infile.log",
Prompt => '/\Q$switch_name\E#\s?$/'
);
(它查找shell提示符以了解命令已完成)。
答案 1 :(得分:0)
由于cmd()
的不稳定性,我转而使用waitfor(String => $string)
。
下面的新脚本:
foreach (@linksys_sps){
my $file = sprintf($folder."/".$_);
print ("Create file ",$file,"\n");
system "touch $file";
my $string = sprintf($_."#");
print ("Prompt String is ",$string,"\n");
print ("Connecting to ",$_,"\n");
my $telnet = new Net::Telnet (
Timeout=>20,
Errmode=>'return',
Input_Log => "infile.log"
);
$telnet->open($_);
if ($telnet->errmsg){
print "Can't connect to " . $_ . " Error: " . $telnet->errmsg . "\n";
} else {
$telnet->waitfor('/User Name:$/i');
$telnet->print('admin');
$telnet->waitfor('/Password:$/i');
$telnet->print('password');
$telnet->waitfor(String => $string );
print ("Set Backup Terminal Variable ",$_,"\n");
$telnet->print("terminal datadump");
$telnet->waitfor(String => $string );
print ("Read configuration ",$_,"\n");
$telnet->print('sh run');
my @config = $telnet->waitfor(String => $string );
print ("Write configuration ",$_," to file ",$file,"\n");
open my $fh, '>', $file or die "Cannot open file: $!";
foreach my $config (@config) {
print $fh "$config\n";
}
close $fh;
print ("Set Default Terminal Variable ",$_,"\n");
$telnet->print('no terminal datadump');
$telnet->waitfor(String => $string );
$telnet->print('exit');
}
}