Skip to content

Instantly share code, notes, and snippets.

@backslash7
Last active December 11, 2019 23:23
Show Gist options
  • Save backslash7/6182103 to your computer and use it in GitHub Desktop.
Save backslash7/6182103 to your computer and use it in GitHub Desktop.
Script for parsing Nagios object.cache file and returning it as JSON.
<?php
header( 'Content-type: application/json;' );
// Change it according to your nagios.cfg
$data = file_get_contents( '/var/ramdrive/objects.cache' );
$matches = array();
$object_matches = array();
$output = array();
preg_match_all( '/(?|define (?<section>\w+) \{\n([^\}]+)+)/i', $data, $matches );
foreach ( $matches['section'] as $object_id=>$section_name ) {
$parsed_object = array();
$object_data = $matches[2][$object_id];
preg_match_all( '/\s+(?<key>\w+)\s+(?<value>.+)/', $object_data, $object_matches );
foreach($object_matches['key'] as $key_index => $key_name) {
if($key_name == 'members') {
$value_data = explode( ",", $object_matches['value'][$key_index] );
} else {
$value_data = $object_matches['value'][$key_index];
}
$parsed_object[$key_name] = $value_data;
}
$object_name = $section_name . '_name';
$output[$section_name][$parsed_object[$object_name]] = $parsed_object;
}
echo json_encode( $output );
Copy link

ghost commented Dec 11, 2019

Thanks a lot. This was very helpful.
Updated the code to disregard comments ("#" ) from Nagios objects file.

function parseNagios($filePath)
{
// $data = file_get_contents($filePath);
$clean = array();
$lines = file($filePath);
foreach ($lines as $word) {
if ((substr($word, 0, 1) === "#")) {
} else {
array_push($clean, $word);
}
}
// console_log(implode($clean));
$data = implode($clean);

$matches = array();
$object_matches = array();
$output = array();
preg_match_all( '/(?|define (?

\w+) {\n([^\}]+)+)/i', $data, $matches );
foreach ( $matches['section'] as $object_id=>$section_name ) {
$parsed_object = array();
$object_data = $matches[2][$object_id];
preg_match_all( '/\s+(?\w+)\s+(?.+)/', $object_data, $object_matches );
foreach($object_matches['key'] as $key_index => $key_name) {
if($key_name == 'members') {
$value_data = explode( ",", $object_matches['value'][$key_index] );
} else {
$value_data = $object_matches['value'][$key_index];
}
$parsed_object[$key_name] = $value_data;
}
$object_name = $section_name . '_name';
$output[$section_name][$parsed_object[$object_name]] = $parsed_object;
}
return json_encode($output);

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment