2011-12-14 93 views
0

我有这个脚本来读取设备列表并发送命令。但目前它只读取第一个设备并发送命令,忽略其余部分。我错过了什么?在多个设备上发送命令

#!\usr\bin\Perl\bin\perl 
use warnings; 
use strict; 
use NET::SSH2; 
use MIME::Base64; 
my $host = "C:/temp/devices.txt"; # input file 
my $user = "XXX"; # your account 
my $pass = "XXXXXX"; # your password 64 bit mime 
my $ssh2 = Net::SSH2->new(); 
my $result = "C:/temp/result.txt"; # output file 
$ssh2->debug(1); # debug on/off 
open(List, '<', "$host") or die "$!"; 
while(<List>) { 
    chomp $_; 
    $ssh2->connect("$_") or die "Unable to connect host [email protected] \n"; 
    my $dp=decode_base64("$pass"); 
    $ssh2->auth_password("$user","$dp"); 
    my $chan = $ssh2->channel(); 
    $chan->exec('sh run'); 
    my $buflen =100000; 
    my $buf = '0' x $buflen; 
    my $read = $chan->read($buf, $buflen); 
    warn 'More than ', $buflen, ' characters in listing' if $read >= $buflen; 
    open OUTPUT, ">", "$result"; 
    print OUTPUT "HOST: $_\n\n"; 
    print OUTPUT "$buf\n"; 
    print OUTPUT "\n\n\n"; 
    print OUTPUT 
    close (List); 
    $chan->close(); 
} 

回答

4
close(List); 

应该是右括号之后。

4

您正在关闭while()循环内的文件句柄。移动close(List)所以它的while()之外:

while(<List>) { 
    ... 
} 
close(List); 

编辑:我只注意到你也这样做,你的while()循环中:

open OUTPUT, ">", "$result"; 

这将导致你的输出文件是每次都通过循环覆盖,所以它只有最后一个命令的结果。您既可以移动open()/close()外循环,或追加方式打开文件:

open OUTPUT, '>>', $result; 

你还没有检查,看是否open()成功;您应该在open()声明的末尾放置or die $!

+0

谢谢,这解决了第一个问题。读取第二个设备列表,但现在无法连接到第二个设备出现错误“无法连接到主机” – Daniel 2011-12-14 19:17:06

7

您不应该在您的while循环内关闭List文件句柄。将close (List);一行移动到大括号后:

open(List, '<', "$host") or die "$!"; 
while(<List>) { 
    # ⋮ 
} 
close (List); 
+0

谢谢,这解决了我的主要问题,现在我的脚本无法连接到列表中的第二个和其余设备 – Daniel 2011-12-14 19:22:52