Last active
August 29, 2015 14:17
-
-
Save onjin/6e36b3d8eef86831720b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| """ | |
| # nagios configuration | |
| 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 | |
| } | |
| define command { | |
| command_name notify-service-by-slack | |
| command_line /usr/local/bin/slack_nagios.py -field slack_channel=#alerts | |
| } | |
| define command { | |
| command_name notify-host-by-slack | |
| command_line /usr/local/bin/slack_nagios.py -field slack_channel=#ops | |
| } | |
| # add slack to f.i. admins contact group | |
| define contactgroup { | |
| contactgroup_name admins | |
| alias Nagios Administrators | |
| members root,slack | |
| } | |
| """ | |
| import argparse | |
| import os | |
| import urllib | |
| import urllib2 | |
| import sys | |
| SLACK_DOMAIN = 'yourteam.slack.com' | |
| SLACK_TOKEN = 'YourToken' | |
| parser = argparse.ArgumentParser(prog='slack_nagios') | |
| parser.add_argument( | |
| '-f', '--field', action='append', type=list, nargs='+' | |
| ) | |
| # command line opts | |
| args = parser.parse_args() | |
| vars = {} | |
| if args.field: | |
| for field in args.field: | |
| print ''.join(field[0]) | |
| field, value = ''.join(field[0]).split('=') | |
| vars[field] = value | |
| # nagios vars | |
| for k, v in os.environ.items(): | |
| if k.startswith(('NAGIOS_', 'ICINGA_')): | |
| vars[k.split('_', 1)[1]] = v | |
| vars['slack_version'] = '1.1' | |
| data = urllib.urlencode(vars) | |
| req = urllib2.Request( | |
| 'https://{}/services/hooks/nagios?token={}'.format(SLACK_DOMAIN, SLACK_TOKEN), | |
| data=data | |
| ) | |
| sys.stderr.write('Request:\n{}\n'.format(req.get_full_url())) | |
| sys.stderr.write('Request data:\n{}\n'.format(data)) | |
| try: | |
| f = urllib2.urlopen(req) | |
| response = f.read() | |
| sys.stderr.write('Response:\n{}\n'.format(response)) | |
| except urllib2.HTTPError as e: | |
| sys.stderr.write('Error:\n{}\n'.format(e.read())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment