Perl脚本检测一个域名是否有效(perl 文件判断)太疯狂了

随心笔谈2年前发布 编辑
187 0
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买


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”;
}

© 版权声明

相关文章