主页 > 知识库 > Perl脚本检测一个域名是否有效

Perl脚本检测一个域名是否有效

热门标签:外呼电信系统 电话机器人哪里有卖 智能机器人电销神器 万利达百货商场地图标注 热门电销机器人 惠州龙门400电话要怎么申请 okcc外呼系统怎么调速度 上海企业外呼系统 河南虚拟外呼系统公司

脚本功能:通过ICMP Ping或TCP/SYN探测指定的域名,探测前检测域名是否有效。

file: check.host.pl

#!/usr/bin/perl

use 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 OK
sub 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.jb51.net
ERR: query 2013.jb51.net failed: NXDOMAIN
2013.jb51.net is DOWN !

# ./check.host.pl www.jb51.net
ACK Reply from www.jb51.net[173.255.214.254] time=307.04 ms
www.jb51.net is online !

# ./check.host.pl jb51.net icmp
Echo Reply from jb51.net[173.255.214.254] time=205.61 ms
jb51.net is online !

# ./check.host.pl chinagfw.com icmp
PING Request for chinagfw.com timed out.
chinagfw.com is DOWN !

标签:合肥 淮安 周口 秦皇岛 绵阳 百色 绥化 周口

巨人网络通讯声明:本文标题《Perl脚本检测一个域名是否有效》,本文关键词  Perl,脚本,检测,一个,域名,;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 下面列出与本文章《Perl脚本检测一个域名是否有效》相关的同类信息!
  • 本页收集关于Perl脚本检测一个域名是否有效的相关信息资讯供网民参考!
  • 推荐文章