Templated mail for nagios / centreon.

This command enables you to dynamicly create a nice templated mail.

Save code below into a file inside the /usr/local/nagios/libexec/mailbytpl.php

On linux you can use the vi command to do so; i.e. $>vi /usr/local/nagios/libexec/mailbytpl.php

#!/usr/bin/php

<?php

// Lets define the defaults //
$showman = false;
$tpldata = false;
$debug = false;
$settings['from'] = 'centreon@amis.nl';
$settings['type'] = 'notification';
$settings['host'] = '{hostname?}';
$settings['reply'] = 'NULL';

// Dont change anything below! //
// Find and sort all the commandline arguments //
// Make a distinct difference between known settings and arguments later to be passed into the template //

if(@is_array($argv)){
// Define that the mail setting isnt passed till we realy found it in the argv
$settings['mail'] = false;
foreach($argv as $value){
$keyval = explode("=", $value);
if(array_key_exists('0', $keyval)){
$key = str_replace('--', '', $keyval[0]);
if(array_key_exists('1', $keyval)){
$val = $keyval[1];
}else{
$val = NULL;
}
}
// Default settings we want to fetch //
switch ($key){
case 'mail':
$settings['mail'] = true;
break;
case 'tplfile':
$settings['tplfile'] = $val;
break;
case 'to':
$settings['to'] = $val;
break;
case 'from':
$settings['from'] = $val;
break;
case 'type':
$settings['type'] = $val;
break;
case 'host':
$settings['host'] = $val;
break;
case 'reply':
$settings['reply'] = $val;
case 'verbose':
$debug=true;
break;
default:
                                // Next to the defaults we fetch additional values...
if(!strstr($key, 'mailbytpl.php')){
$arguments[$key] = $val;
}
}
$keyval = '';
$key = '';
$val = '';
}
$arguments['DATE'] = date('Y-m-d H:i:s');
}else{
// If we got no args (default {basename}.ext is allways passed, still need to fix that.//
// Consider this the spaceholder😉 //
$showman = true;
}
// Validate if all the needed settings where found //
if(!empty($settings['mail']) && !empty($settings['tplfile']) && !empty($settings['to'])){
// Lets try to open the template file//
if($settings['mail']){
if($settings['tplfile']){
//Does the directory exist?//
if(is_dir(dirname($settings['tplfile']))){
if(opendir(dirname($settings['tplfile']))){
if(is_file($settings['tplfile'])){
$tpldata = file($settings['tplfile']);
}else{
die('ERR::Template file doesnt exist or couldnt be opened');
}
}else{
die('ERR::Template file directory coudnt be opened. please verify the rights!');
}
}else{
die('ERR::Template file directory doesnt exist. please verify its existance!');
}
}else{
$showman = true;
}
}else{
$showman = true;
}
// If we have content from the template file, we need to add the information too it //
if($tpldata){
if(count($tpldata) >= 1){
// If we found more then 1 rule we can continue //
// Lets Generate tablerows too place in the template //
$maildata = '';
$cc = '0';
foreach($arguments as $key => $value){
$maildata .= '
<tr>
<td class="datahead'.$cc.'">'.$key.'</td>
<td class="datacontent'.$cc.'">'.$value.'</td>
</tr>
';
$cc++;
}
$maildata .= '<!--Generated by mailbytemplate.php for nagios by AMIS Services BV.-->'."\r\n";
$mailbody ='';
// If there is an element called $DATAROWS$ then insert the pregenerated block//
foreach($tpldata as $lineno => $line){
$pattern = '$DATAROWS$';
$subject = $line;
if(preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE)){
//if there is a match we match it using the arguments//
//Match is found using $matches[0][0]//
$line = str_replace('$DATAROWS$', $maildata, $line);
}
$mailbody .= $line."\r\n";
}
}else{
// We could have loaded an empty file, lets tell the user! //
die('Template file was found to be empty');
}
}
if($mailbody){
                // You can add any header you like...
                $headers ="MIME-Version: 1.0 \r\n";
                $headers.="From: Centreon <".$settings['from'].">\r\n";
                $headers.="Reply-To: ".$settings['reply']." \r\n";
                $headers.="X-Mailer: PHP/".phpversion()."\r\n";
$headers.="Content-type: text/html; charset='us-ascii' \r\n";
$subject =$settings['type'].":: Notification from ".$settings['host']." ...";
mail($settings['to'], $subject, $mailbody, $headers);
}
}else{
$showman = true;
}

if($showman){
// If the mail command isnt found then show the manual //
echo "Using this module is fairly simple, first edit the mainfile mailbytpl.php and alter the defaults \r\n";
echo "Then run the file like the example using the required settings and adding your own using this \r\n";
echo "Format...\r\n";
echo "\r\n\r\n";
echo "{pathtofile}/mailbytpl.php [args]\r\n";
echo "\r\n\r\n";
echo "Valid arguments\r\n";
echo "\t--mail\t\t\t\t\t'Tell the script to execute the mail functionality'\r\n";
echo "\t--tplfile=[path-to-template]\t\t'The path the the template file that should be used by this script'\r\n";
echo "\t--to=[valid@mail.ext]\t\t\t'A valid mailaddress of the receipient,\$CONTACTMAIL$ within nagios\r\n";
echo "\t--from=[valid@mail.ext]\t\t\t'A valid from addres to exclude it from your junkmail folder'\r\n";
echo "\t--reply=[valid@mail.ext]\t\t'Used as reply-to header to redirect mail to different mailboxes. Defaults to 'NULL'\r\n";
echo "\t--type=[NOTIFICATIONTYPE]\t\t'Used in the subject of the mail i.e. [type]::notification for [host]'\r\n";
echo "\t--host=[HOSTNAME]\t\t\t'Used in the subject of the mail i.e. [type]::notification for [host]'\r\n";
echo "\r\n\r\n";
echo "Add your information to the template by adding additional custom entries. using the following syntax;\r\n";
echo "\t--KEY=VALUE\r\n";
echo "\r\n\r\n";
echo "Example for nagios:\r\n";
echo "\$USER1$/mailbytpl --mail --tplfile=\$USER1$\mail.tpl --to=example@mail.nl --from=example@mail.nl --reply=no-reply@mail.nl\r\n";
echo "--type=\$NOTIFICATIONTYPE$ --host=\$HOSTNAME$ --IP=\$HOSTADDRESS$ --DOWNTIME=\$HOSTDOWNTIME$ --YOUROTHERVAR=\$VALUE$ \r\n";
echo "\r\n\r\n\r\nScript by : Chris Gralike\r\nCompany : AMIS Services BV\r\n GPL:2009©\r\n";
}
?>

Next you can configure the command into centreon as a ‘notification’ command that takes the following commands:

–mail                                                         Should be set, enables the mail functionality
–tplfile=[path to template]                  ‘The is the html template that will be used
–to=[valid@email.com]                       Set the receipient
–from=[valid@email.com]                  Set the sender
–reply=[valid@email.com]                  Set the return-path
–type=[NOTIFICATIONTYPE]          used in the subject of the mail.
–host=[HOSTNAME]                           used in the subject of the mail.
–[KEY]=[VALUE]                                  add additional information to the template, these fields are autofilled if used in the template.

example:

$USER1$/mailbytpl --mail --tplfile=\$USER1$\mail.tpl --to=example@mail.nl --from=example@mail.nl --reply=no-reply@mail.nl --type=\$NOTIFICATIONTYPE$ --host=\$HOSTNAME$ --IP=\$HOSTADDRESS$ --DOWNTIME=\$HOSTDOWNTIME$

Next create a template file to point to. I called mine mail.tpl

<html>
<head>
<title>Network notification</title>
<style>
body {background-color:#999; text-align:left; font-family:verdana;}
table{border:1px solid #020245; width:100%;}
th{background-color:#020245; color:#fff; border-bottom:1px solid #020245; text-align:left;}
td{border-bottom:1px solid #020245; background-color:#ccc; font-size:11px;}
tr{height:20px;}
#1{border-style:none; background-color:#ccc;}
.2{width:150px;  font-size:12px; font-weight:bold;}
.3{width:3px;}
</style>
</head>
<body>
<table cellspacing=0 align='center'>
$DATAROWS$</table>
</body>
</html>

Well hope this was usefull for ya😉

#!/usr/bin/php
<?php
// Lets define the defaults //
$showman = false;
$tpldata = false;
$debug = false;
$settings[‘from’] = ‘centreon@amis.nl’;
$settings[‘type’] = ‘notification’;
$settings[‘host’] = ‘{hostname?}’;
$settings[‘reply’] = ‘NULL’;
// Dont change anything below! //
// Find and sort all the commandline arguments //
// Make a distinct difference between known settings and arguments later to be passed into the template //
if(@is_array($argv)){
        // Define that the mail setting isnt passed till we realy found it in the argv
        $settings[‘mail’] = false;
        foreach($argv as $value){
                $keyval = explode(“=”, $value);
                if(array_key_exists(‘0’, $keyval)){
                        $key = str_replace(‘–‘, ”, $keyval[0]);
                        if(array_key_exists(‘1’, $keyval)){
                                $val = $keyval[1];
                        }else{
                                $val = NULL;
                        }
                }
                // Default settings we want to fetch //
                switch ($key){
                        case ‘mail’:
                                $settings[‘mail’] = true;
                                break;
                        case ‘tplfile’:
                                $settings[‘tplfile’] = $val;
                                break;
                        case ‘to’:
                                $settings[‘to’] = $val;
                                break;
                        case ‘from’:
                                $settings[‘from’] = $val;

About Chris Gralike

Momenteel ben ik manager van de afdeling business continuity bij de zakelijke IT dienstverlener AMIS Services BV. Sinds 2003 ben ik actief in de ICT branche. Tussen 2003 en nu heb ik verschillende rollen vervuld. In de rollen: systeem- en netwerkbeheer, system engineer, servicemanager en nu practice manager ben ik in contact gekomen met uiteenlopende technologieën, methodologieën, ideeën, oplossingen en innovaties. Een rijke ervaring waarmee ik de klanten van Conclusion en AMIS elke dag probeer te ondersteunen. Mijn credo: 'Altijd opzoek een win-win tussen business en technologie.'

Posted on June 9, 2009, in Apache 2.2 Windows, centreon, Linux, Nagios / Centreon, Network Monitoring, PHP and tagged , , , , , , , , , , , , , , , . Bookmark the permalink. 5 Comments.

  1. WORKS GREAT! will help me in notification solutions on nagios/centreon

  2. So is this intended to replace the default email template for a nagios/centreon implementation? I’m stricken by the fact that my Linux administration skills are fairly mediocre so I’m not sure what I need to do to change the god aweful email template.

  3. Hi Brian, The script was intended for just that. I have updated the article with additional instructions.

    rgrds, Chris

  4. Hi There

    Great help, however I am running CES. I changed the command I thought was correct but I still got the old email. Where do you change this to send via the template?

    • Hi Ryan,
      Im not familiar with CES. If its anything like nagios the notification is also configured using an external command. Its this portion that needs to be changed.

      Please be advised that nagios is used as an scheduling engine in allot monitoring tools, but each with their own implementation. It might well be that an alternative notification method is implemented.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: