Skip to content

Instantly share code, notes, and snippets.

@matt448
Last active February 13, 2023 15:38
Show Gist options
  • Star 58 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save matt448/8200821 to your computer and use it in GitHub Desktop.
Save matt448/8200821 to your computer and use it in GitHub Desktop.
Script to post Nagios notifications into a Slack channel
#!/bin/bash
# This script is used by Nagios to post alerts into a Slack channel
# using the Incoming WebHooks integration. Create the channel, botname
# and integration first and then add this notification script in your
# Nagios configuration.
#
# All variables that start with NAGIOS_ are provided by Nagios as
# environment variables when an notification is generated.
# A list of the env variables is available here:
# http://nagios.sourceforge.net/docs/3_0/macrolist.html
#
# More info on Slack
# Website: https://slack.com/
# Twitter: @slackhq, @slackapi
#
# My info
# Website: http://matthewcmcmillan.blogspot.com/
# Twitter: @matthewmcmillan
#Modify these variables for your environment
MY_NAGIOS_HOSTNAME="nagios.yourdomain.com"
SLACK_HOSTNAME="yourslack.slack.com"
SLACK_TOKEN="xyxyxyourslackkey"
SLACK_CHANNEL="#alerts"
SLACK_BOTNAME="nagios"
#Set the message icon based on Nagios service state
if [ "$NAGIOS_SERVICESTATE" = "CRITICAL" ]
then
ICON=":exclamation:"
elif [ "$NAGIOS_SERVICESTATE" = "WARNING" ]
then
ICON=":warning:"
elif [ "$NAGIOS_SERVICESTATE" = "OK" ]
then
ICON=":white_check_mark:"
elif [ "$NAGIOS_SERVICESTATE" = "UNKNOWN" ]
then
ICON=":question:"
else
ICON=":white_medium_square:"
fi
#Send message to Slack
curl -X POST --data "payload={\"channel\": \"${SLACK_CHANNEL}\", \"username\": \"${SLACK_USERNAME}\", \"text\": \"${ICON} HOST: ${NAGIOS_HOSTNAME} SERVICE: ${NAGIOS_SERVICEDISPLAYNAME} MESSAGE: ${NAGIOS_SERVICEOUTPUT} <https://${MY_NAGIOS_HOSTNAME}/cgi-bin/nagios3/status.cgi?host=${NAGIOS_HOSTNAME}|See Nagios>\"}" https://${SLACK_HOSTNAME}/services/hooks/incoming-webhook?token=${SLACK_TOKEN}
@GaryRogers
Copy link

Here's a bash function that does something similar, though not Nagios specific.

# ==[ printSlack ]=============================================================
# Function to send output from the commandline to Slack.
#
# @parameter string $LEVEL   INFO/ERROR/WARNING message. Changes emoji
# @parameter string $MESSAGE Message to send to slack. 
printSlack()
{
  SLACK_HOSTNAME=${SLACK_HOSTNAME-'oops.slack.com'};
  SLACK_TOKEN=${SLACK_TOKEN-'oops'};
  SLACK_CHANNEL=${SLACK_CHANNEL-'#devops'};
  SLACK_BOTNAME=${SLACK_BOTNAME-$(hostname -s)};
  SLACK_BOTEMOJI=${SLACK_BOTEMOJI-':computer:'}

  SEVERITY=${1-'INFO'};
  ICON=':slack:';

  case "$SEVERITY" in
    INFO)
      ICON=':page_with_curl:';
      shift;
      ;;
    WARN|WARNING)
      ICON=':warning:';
      shift;
      ;;
    ERROR|ERR)
      ICON=':bangbang:';
      shift;
      ;;
    *)
      ICON=':slack:';
      ;;
  esac

  MESSAGE=$@;

  PAYLOAD="payload={\"channel\": \"${SLACK_CHANNEL}\", \"username\": \"${SLACK_BOTNAME}\", \"text\": \"${ICON} ${MESSAGE}\", \"icon_emoji\": \"${SLACK_BOTEMOJI}\"}";
  CURL_RESULT=$(curl -s -S -X POST --data-urlencode "$PAYLOAD" https://${SLACK_HOSTNAME}/services/hooks/incoming-webhook?token=${SLACK_TOKEN});

  if [ -z "$CURL_RESULT" ]; then
    return 0;
  else
    return 1;
  fi

}

@ryana
Copy link

ryana commented Aug 7, 2015

I'm a little dense when it comes to nagios, and I find the docs a little rough. Can you give me any quick guidance on where exactly to put this file and how to hook it into nagios? :)

@iwelch82
Copy link

iwelch82 commented Nov 3, 2015

I had the same issue with the Perl integration from Slack...... you would think they would update it....
I'm not sure if slack has changed their WebHooks recently or not but I had to use the format. 'https://hooks.slack.com/services/token' in order to make this work. Thanks for the code!

@Azhars
Copy link

Azhars commented Nov 9, 2015

The perl script works fine, just need to use this configuration with older versions and Nagios Core, you'll need to pass the variables as so:

define command {
command_name notify-service-by-slack
command_line /usr/local/bin/slack_nagios.pl -field slack_channel=#alerts -field HOSTALIAS="$HOSTNAME$" -field SERVICEDESC="$SERVICEDESC$" -field SERVICESTATE="$SERVICESTATE$" -field SERVICEOUTPUT="$SERVICEOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
}

define command {
command_name notify-host-by-slack
command_line /usr/local/bin/slack_nagios.pl -field slack_channel=#ops -field HOSTALIAS="$HOSTNAME$" -field HOSTSTATE="$HOSTSTATE$" -field HOSTOUTPUT="$HOSTOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
}

@uncelvel
Copy link

Hi all
Im Using Nagios Core, when i add a config of slack

Step 1 Download slack_nagios.pl

wget https://raw.github.com/tinyspeck/services-examples/master/nagios.pl
cp nagios.pl /usr/local/bin/slack_nagios.pl
chmod 755 /usr/local/bin/slack_nagios.pl

Step 2 Edit slack_nagios.pl

my $opt_domain = "_.slack.com"; # Your team's domain
my $opt_token = "_
**********"; # The token from your Nagios services page

Step 3 Add contact to the /usr/local/nagios/etc/contacts.cfg

define contact {
contact_name slack
alias Slack
service_notification_period 24x7
host_notification_period 24x7
service_notification_options w,u,c,r
host_notification_options d,r
service_notification_commands notify-service-by-slack
host_notification_commands notify-host-by-slack
}

Step 4Add slack to group

define contactgroup{
contactgroup_name systems
alias Systems
members canhdx,sontp,linhndt,slack
}

Step 5 Add command in /usr/local/nagios/etc/commands.cfg

define command {
command_name notify-service-by-slack
command_line /usr/local/bin/slack_nagios.pl -field slack_channel=#alerts -field HOSTALIAS="$HOSTNAME$" -field SERVICEDESC="$SERVICEDESC$" -field SERVICESTATE="$SERVICESTATE$" -field SERVICEOUTPUT="$SERVICEOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
}

define command {
command_name notify-host-by-slack
command_line /usr/local/bin/slack_nagios.pl -field slack_channel=#ops -field HOSTALIAS="$HOSTNAME$" -field HOSTSTATE="$HOSTSTATE$" -field HOSTOUTPUT="$HOSTOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
}

Step 6 Restart nagios

But haven't Notification when server, service has problem in Slack Channel... although Notification to mail is OK
Can you tell me what wrong in my config?

@tankhuu
Copy link

tankhuu commented Nov 19, 2015

Hi uncelvel,

Slack notification was working very well with my Nagios Core.
I followed this document https://navigos.slack.com/services/new/nagios

I think there is no problem with your configuration.
Could you try to do these 2 things:

  • Execute this command in your Nagios Server on the command line terminal: /usr/local/bin/slack_nagios.pl -field slack_channel=#ops -field HOSTALIAS="$HOSTNAME$" -field HOSTSTATE="$HOSTSTATE$" -field HOSTOUTPUT="$HOSTOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"

--> And make sure that your slack receive the notification from your nagios server.

  • Did you add that contactgroups into your host definition? Please show me your host configuration.

@awaaziz
Copy link

awaaziz commented Mar 7, 2016

Hello,

I use this script to post shinken notification into slack, but that not fonctionne.

Shinke is a Nagios core, my configuration is :
Contact :
define contact {
contact_name slack
alias Slack
service_notification_period 24x7
host_notification_period 24x7
service_notification_options w,u,c,r
host_notification_options d,r
service_notification_commands notify-service-by-slack
host_notification_commands notify-host-by-slack
}

Command for hots:
define command {
command_name notify-host-by-slack
command_line /usr/local/bin/slack_nagios.pl -field slack_channel=#alerts field HOSTALIAS="$HOSTNAME$" -field HOSTSTATE="$HOSTSTATE$" -field HOSTOUTPUT="$HOSTOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
}

for service

define command {
command_name notify-service-by-slack
command_line /usr/local/bin/slack_nagios.pl -field slack_channel=#alerts field HOSTALIAS="$HOSTNAME$" -field HOSTSTATE="$HOSTSTATE$" -field HOSTOUTPUT="$HOSTOUTPUT$" -field NOTIFICATIONTYPE="$NOTIFICATIONTYPE$"
}

contact group

define contactgroup{
contactgroup_name admins
alias admins
members admin,pagerduty,slack
}

Please can you help me ???

@Sathichowdhury
Copy link

can this be extended to use attachments attribute to pass a json with colors and more formats as a json?

@kaushalshriyan
Copy link

I am using the slack_nagios.pl perl script. I have integrated it with Nagios 4.2.0 to send notifications to Slack. Is there a way to setup @channel in https://raw.githubusercontent.com/tinyspeck/services-examples/master/nagios.pl perl script so that if there are any alert notifications it will pop up in the slack channel.

@tronyx
Copy link

tronyx commented Apr 20, 2017

I have this setup on 4 Nagios instances and it's working great on 3 of the 4. On the 4th one, I am not receiving any notifications for any of my Hosts that begin with eu. Any insight here?

@iarjune
Copy link

iarjune commented Jun 22, 2017

Does anyone know where I can find the source for the Slack Nagios App. 1st I'm looking for what -fields , other than what was already mentioned, are accepted. Specifically I'm looking for a way to integrate LONGSERVICEOUTPUT into the message. The method i'm using is hacky and since the APP doesn't do multi-line the long output is a strain to read.

To hack in the LONG output I'm using the SERVICEOUTPUT field like this

-field SERVICEOUTPUT="$SERVICEOUTPUT$ // $SERVICEPERFDATA$ // $LONGSERVICEOUTPUT$"

The double forward slash is a visual separator for the different blocks of data.

This webhook script uses json and will be my PLAN B.
https://github.com/khera/slack-integrations/blob/master/slack-nagios-notify

Example of Slack message. You notice in this output a "n" where there should be a new line. That is coming from the Nagios macro, i think.

e-compvertica-02/SYS: Raid Array is WARNING: WARNING: 0:0:RAID-1:2 drives:278.875GB:Optimal 0:1:RAID-10:6 drives:2.727TB:Optimal Drives:8 (94 Errors) // // nSLOT=0, Firmware=Online, Media=0, Other=0, Predictive=0, RawSize=931.512 GB, InqueryData=SEAGATE ST1000NM0023 GS0DZ1W1AQ4M nSLOT=1, Firmware=Online, Media=0, Other=0, Predictive=0, RawSize=931.512 GB, InqueryData=SEAGATE ST1000NM0023 GS0DZ1W1ASBB nSLOT=12, Firmware=Online, Media=0, Other=0, Predictive=0, RawSize=279.396 GB, InqueryData=SEAGATE ST9300653SS YS0A6XN5V23S nSLOT=13, Firmware=Online, Media=88, Other=0, Predictive=6, RawSize=279.396 GB, InqueryData=SEAGATE ST9300653SS YS0A6XN5T2EF nSLOT=2, Firmware=Online, Media=0, Other=0, Predictive=0, RawSize=931.512 GB, InqueryData=SEAGATE ST1000NM0023 GS0DZ1W1AQ5F nSLOT=3, Firmware=Online, Media=0, Other=0, Predictive=0, RawSize=931.512 GB, InqueryData=SEAGATE ST1000NM0023 GS0DZ1W1AR0N nSLOT=4, Firmware=Online, Media=0, Other=0, Predictive=0, RawSize=931.512 GB, InqueryData=SEAGATE ST1000NM0023 GS0DZ1W1ASGX nSLOT=5, Firmware=Online, Media=0, Other=0, Predn

@Pilly170
Copy link

In my slack.log i get
` % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed

0 0 0 0 0 289 0 957 --:--:-- --:--:-- --:--:-- 957
0 8 0 8 0 289 12 455 --:--:-- --:--:-- --:--:-- 0
No hooks`

@tjderby
Copy link

tjderby commented May 17, 2018

I apologize if this has been answered somewhere and I missed it. I have Slack notifications working, but some of my hosts send messages like this:
corp-dc01.WinAD/$ is $:
$

For some reason, the variables are not passing correctly. For other alerts, they are fine. And for these alerts, the email works fine. It is just for Slack on some Host Alerts.
Any ideas why this is happening?
Thanks

@Sabrimjd
Copy link

Sabrimjd commented Sep 5, 2018

@tjderby same problem here

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