Thanks for the reply, I had a quick look but I don't think that method would work for us.
I created a quick PHP script which now takes care of this. Code is below if this helps any one else.
*Take a copy of the service cfg files into a new directory.
*Change into the newly created directory.
*Run:
Code: Select all
for file in *.cfg; do php converter.php "$file"; done
This will go through each service.cfg file, and for each host assigned to the service check it will create a new service file for that host (with the original defined settings), saving the file to 'hostname' + 'service description' + '.cfg'.
Code: Select all
<?php
//Load the passed in filename and store the contents of the file in $fileContents
$currentFile = $argv[1];
if(is_null($currentFile)){
die("Invalid file name passed in");
}
$fileContents = file_get_contents($currentFile);
//Script will not process a file that has more than 1 service definition within it
//Check the errors.txt after running
$numberOfServicesInFile = preg_match_all("/^.*\bhost_name\b.*$/m", $fileContents, $counter);
if($numberOfServicesInFile != 1){
file_put_contents("new/errors.txt", "Multiple or no services in file - failed to process {$currentFile}\n", FILE_APPEND | LOCK_EX);
die("Will not process $argv[1]\n");
}
//Find the host_name line and store all hosts in an array
preg_match("/^.*\bhost_name\b.*$/m", $fileContents, $hosts);
$hosts = preg_replace('/\s+/', '', str_replace("host_name", "", $hosts));
$hosts = explode(',', $hosts[0]);
//Store the service definition (everything between {}) in $template
$template = extractBetween($fileContents, "{", "}");
//Get the 'Service Description'
preg_match("/^.*\bservice_description\b.*$/m", $fileContents, $serviceDescription);
$serviceDescription = str_replace("service_description", "", $serviceDescription);
$serviceDescription = trim($serviceDescription[0]);
$serviceDescription = preg_replace('/[^A-Za-z0-9\-]/', '_', $serviceDescription);
//For each host in the array
foreach ($hosts as $host){
//Replace the 'host_name' line with 'host_name' + current $host
$singleHostTemplate = preg_replace("/.*\bhost_name\b.*\n/u", "\n\thost_name\t\t\t$host\n", $template);
$singleHostTemplate = "define service{".$singleHostTemplate;
$singleHostTemplate .= "\n}\n";
//File name of new service file will be 'hostname' + 'service description' + '.cfg'
$fileName = "new/".$host.".cfg";
//Write new service definition to file.
if(file_put_contents($fileName, $singleHostTemplate, FILE_APPEND | LOCK_EX)){
echo "{$fileName} - wrote to file\n";
}else {
file_put_contents("new/errors.txt", "Error writing file {$fileName}", FILE_APPEND | LOCK_EX);
die("Error writing file $fileName - exiting");
}
}
function extractBetween($string, $start, $end) {
$pos = stripos($string, $start);
$str = substr($string, $pos);
$str_two = substr($str, strlen($start));
$second_pos = stripos($str_two, $end);
$str_three = substr($str_two, 0, $second_pos);
$between = trim($str_three);
return $between;
}
?>