So, as promised, here is my DNS change script. This is written in php for a BIND DNS server. Right now it is very simplistic; it is made to change a single A record, but can be adapted to do multiples at once.
This is designed to be used in conjunction with Webmin. Setup a remote monitor in the “System and Server Status” section under “other”.
Webmin will monitor your web server and ensure they are up and returning a webpage that matches a regex statement. If it does go down it runs our php script with the command line parameter of “down”. The script will then change the A record in the bind file to the secondary server’s IP and then restart the bind service. Once the server comes back up, the script runs again with “up” on the command line. The up command sets the a record back to the main server. This is meant to be run on the DNS server itself. This could be adapted to issue the rndc command to reload the single zone if you so wanted.
You will want to set the TTL on the A record down to like 60 seconds.
Click the link below for Webmin setup and the PHP script!
Webmin Setup:
Add type Remote HTTP Service

Then configure as below.

PHP Script. I’m just putting it in the /root folder. Make sure to set it to executable.
= 2) {
if ($argv[1] == 'up') {
//set the A record back to main
echo "up \n";
$FindIT = $Backup;
$SetIT = $Main;
} elseif ($argv[1] == 'down') {
//set the A record to backup
echo "down \n";
$FindIT = $Main;
$SetIT = $Backup;
}
$lineNum = 0;
echo $Path . $Domains . '.hosts' . "\n";
//open the domain file
$lines = file($Path . $Domains . '.hosts');
//open the file for editing
$fp=fopen($Path . $Domains . '.hosts',"w+");
foreach ($lines as $line_num => $line) {
$lineNum = $lineNum + 1;
//increment sequence #
if ($lineNum == 3) {
$line = $line + 1;
$line = " " . $line . "\n";
}
$pos = 0;
//loop through each line checking if it matches $FindIT exactly with the
//last values at the end of the line. If found, change it to $SetIT
$pos = strpos('test' . $line, $FindIT);
if ($pos > 0) {
//we found the line
$line = str_replace($FindIT, $SetIT, $line);
}
//write each line as we loop through
fwrite($fp,$line);
}
//restart bind service
exec('/etc/init.d/named restart');
}
?>

Leave a Reply