Perl脚本实现检测主机心跳信号功能
使用串口通信,在备机端使用如下脚本检测来自主机的心跳信号,一旦未接受次数超过指定记数,备机认为主机DOWN机,自动设置为主机的网络参数,顶替主机提供服务。
#!perl-w usestrict; useWin32::SerialPort; my$port='COM2';#serailportnameregistriedinOS my$count=0;#countnumberofheartbeat-receivingfailture my$max_count=5;#maxfailcounttobetolerated my$interface=' #---------------------------------- #接口IP配置 #---------------------------------- pushdinterfaceip #"local"的接口IP配置 setaddressname="local"source=staticaddr=192.168.6.185mask=255.255.255.0 setaddressname="local"gateway=192.168.6.65gwmetric=0 setdnsname="local"source=staticaddr=192.168.6.112register=PRIMARY adddnsname="local"addr=192.168.6.201index=2 setwinsname="local"source=staticaddr=none popd #接口IP配置结束 ';#netinetrfaceconfiginformation suberrlog{ #logthefailtrueoccuringtime openERR,'>>err.log'; my@time=localtime(); my$time=sprintf("%d",$time[5]+1900) .'-' .sprintf("%d",$time[4]+1) .'-' ."$time[3]" .'' .sprintf("%.2d",$time[2]) .':' .sprintf("%.2d",$time[1]) .':' .sprintf("%.2d",$time[0]); printERR$time."\n"; closeERR; } subipchange{ #changeipaddrress openTMP,'>tmp'; printTMP$interface; closeTMP; eval{ system'netsh-ftmp'; unlink'tmp'; }; if($@){return0;} return1; } my$ob=Win32::SerialPort->new($port)ordie"CANNOTOPEN$port"; #openserialport eval{ #setserialportproperties $ob->baudrate(9600); $ob->parity('none'); $ob->databits(8); $ob->stopbits(1); $ob->handshake('none'); }; if($@){die'SETFAILED';} $ob->write_settingsordie"CANNOTWRITE$portDRIVER"; #writetoportdrivertomakeitactive while(1){ #loopreceivingheartbeatfromremotemachine #changeipaddressafterdesignatedcountoffailture my($length,$result)=$ob->read(10); if($result){ $count=0; }elsif($count==$max_count){ errlog(); if(notipchange()){print'IPCHANGEFAILED';} last; }else{ $count++; } sleep(1); } undef$ob;