2013年5月10日 星期五

perl , ssh2 , vyatta , vbash and remote executio


perl , ssh2 , vyatta , vbash and remote executio


如何使用 perl 寫一支 shell 連入 vyatta OS 內,並下指令 show ????,
並將 結果 自動以 E-Mail 方式寄回給網管人員!

About vyatta

www.vyatta.com or www.vyatta.org

or 我以前發表過的文章如下:
http://www.pczone.com.tw/vbb3/thread/16/147986/


程式範列如下,可依需要自行修改之:

 [xrcd2@centos shell]# cat ssh2-vyatta-show.pl
    
#!/usr/bin/perl
use Net::SSH2;
$ssh=Net::SSH2->new() or die "couldn't make SSH object\n";
#$ssh->debug(1);
$ssh->blocking(1);
print "\n made SSH object\n";
$ssh->connect('xxx.xxx.xxx.xxx') or die "couldn't connect to host\n";
print "\n connected to vyatta-host\n";
$ssh->auth_password('vyatta-id','vyatta-pwd') or die "couldn't authenticate \n";
print "\n \n authenticated vyatta-id \n \n";

print " \n ================== send command ====================== \n ";
$command1 = $ssh->channel();
$command1->exec('vbash -i -c "show version "');

$buflen = 10000;
$show = '0' x $buflen;
$command1->read($show, $buflen);

chomp($show);
print "\n $show";

print " \n \n  =================  end  ============================== \n \n ";

$ssh->disconnect or die "couldn't disconnect\n";

get_mail();

sub get_mail{
 use Encode qw(decode encode_utf8);
 use Encode qw(encode);
 use MIME::Base64;
 use MIME::Lite;
 $foot0=' 自動使用SSH2 到 Vyatta OS 的 Shell ( ssh2 vyatta vbash )  ';
 use Encode qw/from_to/;
 from_to($foot0, "utf8", "big5");
 $line='=====================================================';


 $msg = MIME::Lite->new(
     From     =>'vyatta@xrcd2.com.tw',
     To       =>'xrcd2@xrcd2.com.tw',
     Subject => "show vyatta version ",
     Encoding => 'base64',
     Data     =>"$foot0 \n\n $line \n\n $show \n\n $line\n\n"
 );
 $msg->get_length;
 $msg->attr("content-type.charset" => "UTF8");
 $msg->send('smtp','x.x.x.x');
 print $Mail::SendMail::Error eq "" ? "\n\n send ok! \n\n" : $Mail::SendMail::Error;
}


[root@centos63 shell]# perl  blog-ssh.pl
      
 made SSH object

 connected to vyatta-host


 authenticated vyatta-id


 ================== send command ======================

 Version:      VC6.5R1
Description:  Vyatta Core 6.5 R1
Copyright:    2006-2012 Vyatta, Inc.
Built by:    
autobuild@vyatta.com
Built on:     Fri Nov 16 16:39:16 UTC 2012
Build ID:     1211161646-334fb58
System type:  Intel 32bit
Boot via:     disk
Hypervisor:   VMware
HW model:     VMware Virtual Platform
HW S/N:       VMware-56 4d 5b da 3e 1c d1 93-43 38 03 40 4a 5c e9 29
HW UUID:      564D5BDA-3E1C-D193-4338-03404A5CE929
Uptime:       16:58:35 up  2:11,  1 user,  load average: 0.00, 0.01, 0.05



  =================  end  ==============================
 

send ok!
 [xrcd2@centos shell]#

沒有留言:

張貼留言