Cisco Perl Telnet Script:

A single process Perl program fetches Cisco routers/switches config or other info may take 2 seconds per equipment. If you have 1,000 Cisco routers/switches, it will take 2,000 seconds which will be 33+ minutes. This Perl multi-processes program will save tons of your time to gather info like around 10 seconds. Please enjoy!

1. Successful messages( scalar type ) are stored in hash of hash : $hostinfo{ “$hostname” }->{ “$cmd” }
2. Failed messages( scalar type ) are stored in hash of hash : $hosterrinfo{ “$hostname” }->{ “$cmd” }

#!/usr/bin/perl -w
# This perl script is main to be doing numeric cisco equipment management

use strict;
use IPC::Shareable;

$SIG{ 'CHLD' } = 'IGNORE';

my @hosts = ( ''host name or IP', ''host name or IP' );

my @cmds = ( 'sh geego', 'sh ver', 'sh clock', 'sh queueing', 'sh hosts' );
my $username = 'username';  # cisco telnet username
my $passwd = 'password';   # cisco telnet username
my $enable_passwd = 'enable password';
my %hostinfo = ();
my %hosterrinfo = ();
my @children = ();
my %ipcoptions = ( create => 'yes',
exclusive => 0,
mode => 0644,
destroy => 'yes' );

tie %hostinfo, 'IPC::Shareable', 'good', \%ipcoptions or die "Can't tie %hostinfo.\n";
tie %hosterrinfo, 'IPC::Shareable', 'err', \%ipcoptions or die "Can't tie %hosterrinfo\n";

foreach my $host ( @hosts )
{
my $pid = fork();
die "Can't fork.:$!\n" unless defined( $pid );

if( $pid == 0 ) # this is child process
{
print "Child process is $$\n";

get_info( $host );
exit( 0 );
}
else # This is parent process
{
print "$$ -> Process $pid is processing $host now.\n";
push( @children, $pid );
}
}

foreach ( @children )
{
#my $child_pid = waitpid( $_, 0 );
my $child_pid = wait();
print "Process $_ is done.\n";
}

sub get_info
{
use Net::Telnet::Cisco;  #Special Perl Cisco Telnet module
my ( $hostname ) = @_;

my $cisco = Net::Telnet::Cisco->new( 'Host' => $hostname,
'Errmode'=> 'return' );  #Perl Cisco Telnet Object initialization
$cisco->login( Password => "$passwd" );
$cisco->ignore_warnings;

foreach my $cmd ( @cmds )
{
my @output = $cisco->cmd( "$cmd" );

if( $cisco->errmsg() )
{
$hosterrinfo{ $hostname }->{ $cmd } = $cisco->errmsg();
}
else
{
my $out = join( "", @output );
$hostinfo{ $hostname }->{ $cmd } = $out;
}
}
}

foreach my $host ( keys %hostinfo )
{
foreach my $cmd ( keys %{$hostinfo{ $host }} )
{
print "$host => $cmd =>\n $hostinfo{ $host }->{ $cmd }\n";
}
}

More technical tips see:http://www.geego.com/tech_support/new-tip-list

文章標籤

創作者介紹
創作者 台灣 富捷IT培訓 的頭像
台灣 富捷IT培訓

台灣 富捷 IT 培訓

台灣 富捷IT培訓 發表在 痞客邦 留言(0) 人氣()