0

我创建了一个 telnet 到多个交换机的 perl。我的代码只为多个 Cisco 交换机生成一个日志文件输出。

我应该怎么做才能为每个设备状态创建单独的日志文件(包括 telnet 故障)?以及如何从日志文件名将 IP 转换为主机名?

想要的输出日志文件一一对应,hostname1.log、hostname2.log、hostname3.log……以此类推。

这是我的代码:

#!/usr/bin/perl
use strict;
use warnings;
use Net::Cisco;

my $username="danny";
my $pass="1234";

open (OUTPUT, ">intstatus.log" );
open (IP, "ip.txt") or die $!;

for my $line (<IP>) {
chomp $line;
$line =~ s/\t+//;
print $line, "\n";
SWTELNET($line); # pass $line as the argument to SWTELNET
}
sub SWTELNET {

my $host = shift; # $host is set to the first argument passed in from the above loop
my $t = Net::Telnet::Cisco -> new (
Host => $host,
Prompt => '/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
Timeout => 6,
Errmode => 'return',
) or die "connect failed: $!";

if ($t->login($username,$pass)) {
$t->autopage;
$t->always_waitfor_prompt;

my @supenv=$t->cmd("show ip int br");
my @output = ();
print OUTPUT "$host\n@supenv\n";
 }
}
close(IP);
close(OUTPUT);
4

1 回答 1

1

我没有任何 telnet 设备可供测试,但这至少应该能让你大部分时间。它使用gethostbyaddr()from Socket尝试将 IP 解析回主机名(如果找不到名称,则回退到使用 IP 作为主机名)。它还使用带有词法文件句柄(与裸字句柄相反)的正确的三参数形式打开,并打开一个新的日志文件,用于hostname.log以输入文件中找到的每个主机的格式写入。

use warnings;
use strict;

use Net::Telnet::Cisco;
use Socket;

my $username="danny";
my $pass="1234";

open my $infile, '<', "ip.txt" or die $!;

for my $ip (<$infile>) {
    chomp $ip;
    $ip =~ s/\t+//;

    # resolve IP to hostname if possible

    my $host = gethostbyaddr(inet_aton($ip), AF_INET);

    $host = $ip if ! $host;

    SWTELNET($host);
}

close $infile;

sub SWTELNET {

    my $host = shift;

    my $t = Net::Telnet::Cisco->new(
        Host => $host,
        Prompt => '/(?m:^(?:[\w.\/]+\:)?[\w.-]+\s?(?:\(config[^\)]*\))?\s?[\$#>]\s?(?:\(enable\))?\s*$)/',
        Timeout => 6,
        Errmode => 'return',
    ) or die "connect failed: $!";

    if ($t->login($username,$pass)) {
        $t->autopage;
        $t->always_waitfor_prompt;

        my @supenv=$t->cmd("show ip int br");

        # no need to manually close the file after, as it'll happen
        # automatically as soon as the scope ends

        open my $wfh, '>', "$host.log";
        print $wfh "$host\n@supenv\n";
    }
}
于 2015-12-30T15:37:39.893 回答