Perl脚本检测一个域名是否有效
脚本功能:通过ICMPPing或TCP/SYN探测指定的域名,探测前检测域名是否有效。
file:check.host.pl #!/usr/bin/perl usestrict; useNet::Ping; useNet::DNS; useTime::HiResqw(); $|=1; my$DEFAULT_TIMEOUT=2; my$PING_TIMEOUT=2; my$DNS_TIMEOUT=3; ###查询域名是否有效 subqueryDomain{ my$domain=shift(); my$query=''; my$dns=Net::DNS::Resolver->new( tcp_timeout=>$DNS_TIMEOUT,udp_timeout=>$DNS_TIMEOUT,retry=>1 ); my@nameservers=qw/8.8.8.8114.114.114.114/; $dns->nameservers(@nameservers); eval{ $query=$dns->search($domain,'A'); }; if($@or!$query){ my$err=$dns->errorstring; print"ERR:query$domainfailed:$errn"; returnif($err=~/NXDOMAIN/); } return'OK'; } ###returnnothingisFAILED,otherisOK subpingHost{ my$arg=shift(); return1if(ref$argne'HASH'); my$p; eval{$p=Net::Ping->new($arg->{'proto'},$DEFAULT_TIMEOUT,0)}; if($@){ warn"ERRtocreateNet::Pingobject:$@n"; return; } $p->hires(); my($host,$duration,$hip,$rep,$ret); ###tcp/synping if($arg->{'proto'}eq"syn"){ $p->{port_num}=$arg->{'port'}; $p->ping($arg->{'host'},$PING_TIMEOUT); if(($host,$duration,$hip)=$p->ack()){ printf("ACKReplyfrom$arg->{'host'}[%s]time=%.2fmsn",$hip,$duration*1000); $ret='OK'; }else{ warn"SYNRequestfor$arg->{'host'}timedout.n"; } } ###icmpping else{ ($rep,$duration,$hip)=$p->ping($arg->{'host'},$PING_TIMEOUT); if($rep){ printf("EchoReplyfrom$arg->{'host'}[%s]time=%.2fmsn",$hip,$duration*1000); $ret='OK'; } else{ warn"PINGRequestfor$arg->{'host'}timedout.n"; } } $p->close; undef($p); return$ret; } my$ARG={proto=>'syn',port=>80}; my$host=$ARGV[0]; my$proto=$ARGV[1]; die"Usage:$0[icmp]n"if(!$host); $ARG->{'host'}=$host; $ARG->{'proto'}=$protoif($proto); my$code; if(&queryDomain($host)eq'OK'and$code=&pingHost($ARG)){ print"$hostisonline!n"; } else{ print"$hostisDOWN!n"; }
测试例子:
#./check.host.pl2013.jb51.net ERR:query2013.jb51.netfailed:NXDOMAIN 2013.jb51.netisDOWN! #./check.host.plwww.nhooo.com ACKReplyfromwww.nhooo.com[173.255.214.254]time=307.04ms www.nhooo.comisonline! #./check.host.pljb51.neticmp EchoReplyfromjb51.net[173.255.214.254]time=205.61ms jb51.netisonline! #./check.host.plchinagfw.comicmp PINGRequestforchinagfw.comtimedout. chinagfw.comisDOWN!