Last active
September 25, 2017 09:50
-
-
Save pysysops/a39809f8da4a1c605ab31d834a00d1cf to your computer and use it in GitHub Desktop.
Python script to get current alerts from Sensu API and display at login
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 | |
import sys | |
import urllib | |
import urllib2 | |
import socket | |
import json | |
import argparse | |
import time | |
from urlparse import urlparse | |
# This script is run at login by /etc/profile.d/show_alerts.sh | |
# It let's users know what issues are currently alerting | |
# on the host. | |
def setup(): | |
parser = argparse.ArgumentParser( | |
description='Shows alerts for a host (default: self) in glorious color-vision.', | |
) | |
parser.add_argument('--server', type=str, | |
help='Sensu / uchiwa API server hostname', | |
default='sensu') | |
parser.add_argument('--port', type=int, | |
help='Sensu / uchiwa port', | |
default=4567) | |
parser.add_argument('--host', type=str, | |
help='The host to get alerts for', | |
default=socket.getfqdn()) | |
parser.add_argument('--secure', | |
help='The host to get alerts for', | |
action='store_const', | |
const='https', | |
default='http') | |
return parser.parse_args() | |
def getdata(url): | |
try: | |
req = urllib2.Request(url, None, {'Accept': 'application/json'}) | |
raw = urllib2.urlopen(req, timeout=2).read() | |
data = json.loads(raw) | |
return {'status': 0, 'text': data} | |
except Exception, e: | |
sys.exit(1) | |
def get_color_string(code, message): | |
if code == 0: | |
return "\033[92m%s\033[0m" % (message,) | |
elif code == 1: | |
return "\033[33m%s\033[0m" % (message,) | |
elif code == 2: | |
return "\033[91m%s\033[0m" % (message,) | |
else: | |
return "\033[94m%s\033[0m" % (message,) | |
def main(args): | |
# Get data from Sensu / Uchiwa API | |
event_data = getdata("%s://%s:%d/events/%s" % ( | |
args.secure, | |
args.server, | |
args.port, | |
args.host | |
) | |
)['text'] | |
if not event_data == []: | |
print get_color_string(3, "Current alerts for this host:") | |
for event in event_data: | |
message = "%s: %s" % ( | |
event['check']['name'], | |
event['check']['output'].split('|')[0], | |
) | |
# Trim messages to 80 characters | |
message = (message[:77] + '...') if len(message) > 80 else message | |
print get_color_string(event['check']['status'], message) | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main(setup())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A handy script to run at login. See: https://gist.github.com/pysysops/d813a3f86149c63456fded6e667fac42
Gives output below MOTD:
