PERL threads – PERL 執行緒程式,佈署大量Cisco設備的組態,或收集資訊

此多執行緒 PERL threads 程式,使用 telnet 協定取得每台 Cisco 路由器或交換器之組態或訊息,所需時間約2秒鐘,如果貴公司有 1,000 台 Cisco 設備,一般單執行緒程式恐耗時 2,000 秒相當於 33+ 分鐘,本 PERL threads 程式可同時對所有的 Cisco 設備同時進行存取,所需時間在10秒鐘左右;請各位試試看。

  • 執行成功訊息輸出(scalar type)儲存於hash of hash :
    • $hostinfo{ "主機名稱" }->{ "執行指令" }
  • 執行失敗訊息輸出(scalar type)儲存於hash of hash:
    • $hosterrinfo{ "主機名稱" }->{ "執行指令" }
#!/usr/bin/perl -w 
# This perl threads script is mainly to be doing numeric Cisco equipment management.

use strict;  
use threads; # PERL threads 模組  
use threads::shared; # PERL threads ::shared 模組

my @hosts = ( '主機名稱或IP', '主機名稱或IP' );  
my @threads = ();

# Shared data declaration

my @cmds :shared = ( 'sh geego', 'sh ver', 'sh clock', 'sh queueing', 'sh hosts' );  
my $username :shared = '登入帳號名稱';  # cisco telnet 的帳號  
my $passwd :shared = '登入密碼';     # cisco telnet 的帳號  
my $enable_passwd :shared = 'enable的密碼';  
my %hostinfo :shared = ();  
my %hosterrinfo :shared = ();

foreach my $host ( @hosts )  
{ 
    $hostinfo{ "$host" } = &share( {} ); 
    $hosterrinfo{ "$host" } = &share( {} ); 
    push( @threads, threads->new( \&get_info, $host ) ); 
} 

foreach ( @threads )  
{ 
    $_->join(); 
}

sub get_info  
{ 
    use Net::Telnet::Cisco;  # 特別的 Perl Cisco Telnet的模組 
    my ( $hostname ) = @_;
    my $cisco = Net::Telnet::Cisco->new( 'Host' => $hostname, 
                                         'Errmode'=> 'return' );  # Perl Cisco Telnet的物件初始化 
    $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 ( keys %{$hostinfo{ $host }} ) 
    { 
        print " $host => $_ => $hostinfo{ $host }->{ $_ }"; 
    } 
}