DNS Zone Creation Script
This CLI script was created for the purposes of adding new zones to an internal DNS server I had setup within an office LAN. I basically wanted to setup DNS Zones that were name.lan for internal development environments.
<?php
/*
* Example usage:
* sudo php dns.php create site.lan
*/
class dns {
private $zone, $option, $config;
public function __construct(){
$this->config['named'] = '/etc/bind/named.conf.local'; // named.conf.local file location
$this->config['config_path'] = '/etc/bind/'; // path to store config files
$this->config['network_ip'] = '192.168.1.1'; // internal network ip
$this->detect_sudo();
$this->option = $_SERVER['argv'][1];
$this->zone = $_SERVER['argv'][2];
$options = array('create');
if(in_array($this->option, $options)){
switch($this->option){
case 'create':
echo "Creating DNS zone $this->zone\n";
$this->add_named();
$this->add_config();
$this->restart_bind();
break;
// add other options here...
}
}else{
echo 'Invalid option selected, pick from '.implode(' ', $options)."\n";
}
}
private function detect_sudo(){
$process_info = posix_getpwuid(posix_geteuid());
if($process_info['name'] != 'root'){
echo "Sorry, this needs to be run with sudo!\n";
die;
}
}
// add zone to named.conf.local
private function add_named(){
// get existing file
$named = file_get_contents($this->config['named']);
// add new zone
$named .= "\n";
$named .= 'zone "'.$this->zone.'" {'."\n";
$named .= "\ttype master;\n";
$named .= "\t".'file "'.$this->config['config_path'].'db.'.$this->zone.'";'."\n";
$named .= "};\n";
// save file
if(file_put_contents($this->config['named'], $named)){
echo "zone added to named.conf.local\n";
}else{
echo "There was an error writing to named.conf.local, script haulted.\n";
die;
}
}
// add config file for zone
private function add_config(){
$conf_str = '$TTL 604800
@ IN SOA main.'.$this->zone.'. admin.'.$this->zone.'. (
2008080101 ;serial
04800 ;refresh
86400 ;retry
2419200 ;expire
604800 ;negative cache TTL
)
@ IN NS main.'.$this->zone.'.
@ IN A '.$this->config['network_ip'].'
@ IN MX 10 main.'.$this->zone.'.
main IN A '.$this->config['network_ip'].'
www IN CNAME main';
if(file_put_contents($this->config['config_path'].'db.'.$this->zone, $conf_str)){
echo "zone config file written.\n";
}else{
echo "There was an error writing the zone config file, script haulted.\n";
die;
}
}
// restart bind
private function restart_bind(){
shell_exec('sudo /etc/init.d/bind9 restart');
}
}
new dns;
?>