在多个设备上发送命令

时间:2011-12-14 18:34:15

标签: perl

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

#!\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 $@ \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();
}

3 个答案:

答案 0 :(得分:7)

您不应该在while循环中关闭List文件句柄。将close (List);行移到紧密括号后面:

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

答案 1 :(得分:4)

close(List);

应该在结束括号之后。

答案 2 :(得分:4)

您正在while()循环中关闭文件句柄。移动close(List)使其超出while()

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

修改:我刚刚注意到您在while()循环中也这样做了:

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

这将导致每次循环都会覆盖输出文件,因此它只会包含最后一个命令的结果。您可以将open() / close()移到循环外部,也可以以追加模式打开文件:

open OUTPUT, '>>', $result;

你也没有检查open()是否成功;您应该将or die $!放在open()声明的末尾。