使用環境 perl + cisco (ios) + telnet + smtp + 排程
程式碼如下,請視實務需求自行修改!
#!/usr/bin/perl
($sec,$min,$hour,$day,$mon,$year)=localtime(time);
$mon++;
if (length ($mon) == 1) {$mon = '0'.$mon;}
if (length ($day) == 1) {$day = '0'.$day;}
if (length ($hour) == 1) {$hour = '0'.$hour;}
if (length ($min) == 1) {$min = '0'.$min;}
if (length ($sec) == 1) {$sec = '0'.$sec;}
$year+=1900;
$clock="$year$mon$day$hour$min$sec";
$subname='.txt';
$dir='/root/shell/cisco/';
#設備 IP 請務必正確輸入於下面
@cisco=qw
(
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
);
#設備名稱請輸入於下面以方便做為存檔或郵件示別使用
@hostname=qw
(
Switch-1
Switch-2
Switch-3
Switch-4
Router-1
Router-2
Router-3
Router-4
Router-5
);
for ($x=0;$x<=$#cisco;$x++){
print " \n telnet IP $cisco[$x] HostName $hostname[$x] \n";
print " \n Write File Name is $hostname[$x].$clock$subname \n\n ";
$savefile="$dir$hostname[$x].$clock$subname";
print "\n save $savefile \n\n ";
print " \n No. $x IP $cisco[$x] $hostname[$x] Start Sending command .... \n";
# 使用下面這種方式連入 Cisco 設備
get_cisco();
# show run 的存檔作業
open(write_file,">$savefile") or "open file error";
print write_file "@showrun";
close(write_file);
#使用下面這種方式寄信 show run 的資訊會在郵件本文中,
#如不使用~下面 get_mail()前方請加上 #
get_mail();
sleep 5;
#使用下面這種方式寄信 show run 的資訊會變成以附件的方式傳送,
#如不使~用下面 send_config_file() 前方請加上 #
send_config_file();
sleep 5;
}
sub get_cisco{
use Net::Telnet::Cisco;
$session = Net::Telnet::Cisco->new(Host => "$cisco[$x]",Timeout=>'120');
#使用 ID + PWD login 請使用下一行 , 如不使用~下一行前方請加上 #
#$session->login('login', 'password');
#只使有 pwd login 請使用下一行, 如不使用~下一行前方請加上 #
$session->cmd('xxxxxxxxx');
$session->enable('xxxxxxxxx');
@showrun = $session->cmd('show run ');
$session->close;
}
sub get_mail{
use Encode qw(decode encode_utf8);
use Encode qw(encode);
use MIME::Base64;
use MIME::Lite;
$foot0=' Cisco Devices configuration auto backup ';
use Encode qw/from_to/;
from_to($foot0, "utf8", "big5");
from_to(@showrun, "utf8", "big5");
from_to($clock, "utf8", "big5");
$line='=====================================================';
$msg = MIME::Lite->new(
From =>'cisco-show-run@xrcd2.com.tw',
To =>'xrcd2@xrcd2.com.tw',
Subject => "$hostname[$x].$clock.txt",
Encoding => 'base64',
Data =>"$foot0 \n\n $line \n\n @showrun \n\n $line\n\n"
);
$msg->get_length;
$msg->attr("content-type.charset" => "UTF8");
$msg->send('smtp','smtp.server.ip.address');
print $Mail::SendMail::Error eq "" ? "\n send ok!\n" : $Mail::SendMail::Error;
}
sub send_config_file{
use Mail::Sender;
$sender = new Mail::Sender
{smtp => 'smtp.server.ip.address', from => 'showrun@xrcd2.com.tw'};
$sender->MailFile({to => 'xrcd2@xrcd2.com.tw',
subject => "$hostname[$x].$clock$subname",
msg => "$hostname[$x].$clock$subname",
file => "$dir$hostname[$x].$clock$subname"});
}
下圖為以附加檔案方式將 show run 的資訊寄出!
下圖為將 show run 的資訊顯示在郵件本文中!
沒有留言:
張貼留言