User Tools

Site Tools


monitor_dns_changes_for_hostname

Monitor DNS Changes for Hostname

#!/bin/env perl
use strict;
## Check to see if IP Address or CNAME has changed for a host
## If it has chagned, send message using mail function
 
require Net::DNS;
require MIME::Lite;
 
my %hostname = (
	'cdn.djtunez.net' => [ "ns1.lithiumfox.com", "ns1.lithiumfox.com"],
	);
 
 
for (keys %hostname){
	my $record; 
	my $res = Net::DNS::Resolver->new(
		nameservers	=> $hostname{$_},
		recurse		=> 0,
		debug		=> 0,
	);
 
	my $request = $res->query("$_");
 
	if ($request){
		foreach my $rr ($request->answer){
			if ($rr-> type eq "CNAME"){
				$record = $rr->cname;
			}
			elsif ($rr->type eq "A"){
				$record = $rr->address;
			}
		}
	}
	checkDifference($record,$_);
}
 
sub checkDifference {
 
	my ($record, $hostname) = @_;
	my $statepath = "/var/run/dnscheck";
	my $state = "$hostname.state";	
 
	open STATE, "<$statepath/$state" or die $!;
	while (<STATE>){
		chomp;
		my $sstate = $_;
		close STATE;
		if ($sstate ne $record){
			print "$hostname DNS record has changed from $sstate -> $record\n";
			my $msgbody = "$hostname DNS record has changed from $sstate -> $record\n";
			mail($msgbody, $hostname);
			open STATE, ">$statepath/$state" or die $!;
			print STATE $record;
			close STATE;
			}
		}
}
 
 
sub mail { 
 
	my ($msgbody, $hostname) = @_;
	my $subject = "$hostname DNS Record Changed!";
	my @mailto =  [ '[email protected]' ];
 
	my $msg = MIME::Lite->new(
		Subject => $subject,
		To	=> @mailto,
		Type	=> 'text/html',
		Data	=> $msgbody,
	);
	$msg->send();
}
monitor_dns_changes_for_hostname.txt · Last modified: 2011/05/10 10:48 by jt