我创建了一个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);
答案 0 :(得分:1)
我没有任何telnet设备可以测试,但这至少可以帮到你。它使用来自Socket的gethostbyaddr()
来尝试将IP解析回主机名(如果找不到名称,则回退到使用IP作为主机名)。它还使用正确的三参数形式的open和词法文件句柄(而不是裸字句柄),并打开一个新的日志文件,以格式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";
}
}