Perl脚本检测一个域名是否有效
技术  /  管理员 发布于 6年前   276
脚本功能:通过ICMP Ping或TCP/SYN探测指定的域名,探测前检测域名是否有效。
file: check.host.pl#!/usr/bin/perluse strict;use Net::Ping;use Net::DNS;use Time::HiRes qw();$| = 1;my $DEFAULT_TIMEOUT = 2;my $PING_TIMEOUT = 2;my $DNS_TIMEOUT = 3;### 查询域名是否有效sub queryDomain { 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.8 114.114.114.114/; $dns->nameservers(@nameservers); eval {$query = $dns->search($domain,'A'); }; if ($@ or ! $query) { my $err = $dns->errorstring ; print "ERR: query $domain failed: $errn"; return if ($err =~ /NXDOMAIN/); } return 'OK';}### return nothing is FAILED, other is OKsub pingHost { my $arg = shift(); return 1 if (ref $arg ne 'HASH'); my $p; eval { $p = Net::Ping->new($arg->{'proto'},$DEFAULT_TIMEOUT,0) }; if ($@) { warn "ERR to create Net::Ping object: $@n"; return; } $p->hires(); my ($host,$duration,$hip,$rep,$ret); ### tcp/syn ping if ($arg->{'proto'} eq "syn") {$p->{port_num} = $arg->{'port'};$p->ping($arg->{'host'},$PING_TIMEOUT);if (($host,$duration,$hip) = $p->ack()) { printf("ACK Reply from $arg->{'host'}[%s] time=%.2f msn", $hip, $duration * 1000); $ret = 'OK'; } else { warn "SYN Request for $arg->{'host'} timed out.n";} } ### icmp ping else { ($rep,$duration,$hip) = $p->ping($arg->{'host'},$PING_TIMEOUT); if ($rep) { printf("Echo Reply from $arg->{'host'}[%s] time=%.2f msn", $hip, $duration * 1000); $ret = 'OK'; }else { warn "PING Request for $arg->{'host'} timed out.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'} = $proto if ($proto);my $code;if (&queryDomain($host) eq 'OK' and $code = &pingHost($ARG)) { print "$host is online !n";}else { print "$host is DOWN !n";}
测试例子:
# ./check.host.pl 2013..net.cnERR: query 2013..net.cn failed: NXDOMAIN2013..net.cn is DOWN !# ./check.host.pl ACK Reply from [173.255.214.254] time=307.04 ms is online !# ./check.host.pl .net.cn icmpEcho Reply from .net.cn[173.255.214.254] time=205.61 ms.net.cn is online !# ./check.host.pl chinagfw.com icmpPING Request for chinagfw.com timed out.chinagfw.com is DOWN !
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号