Created
April 15, 2015 02:48
-
-
Save idlethreat/be2e92b465744bf78790 to your computer and use it in GitHub Desktop.
graylog-search-for-stale-devices
This file contains 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 requests | |
import sys | |
from gelfclient import UdpClient | |
# Please install the latest Python Requests and gelfclient libraries to take advantage of this script | |
# http://docs.python-requests.org/ | |
# https://github.com/Graylog2/gelfclient | |
# define the Graylog server, user and password to perform the query | |
myGraylogServer = "ip_of_graylog_server" | |
myGraylogUsername = "username" | |
myGraylogPassword = "userpass" | |
nowTime = "86400" # closest time from now. Default to 86400 seconds | |
previousTime = "604800" # furthest time to search. Default to last week (604800 seconds) | |
def send_gelf_message(g_subject,g_body): | |
gelf_server = myGraylogServer | |
gelf = UdpClient(gelf_server, port=12201, mtu=8000, source='stale_devices') | |
data = {} | |
data['short_message'] = g_subject | |
data['full_message'] = g_body | |
gelf.log(data) | |
# This function will query the target Graylog server, pull dictionary of sources | |
# then will convert the library into a list. | |
def queryGraylog(timeFrame): | |
urlBuild = 'http://' + str(myGraylogServer) + ':12900/sources?range=' + str(timeFrame) | |
r = requests.get(urlBuild, auth=(myGraylogUsername, myGraylogPassword)) | |
sourcesList = [] | |
for key, value in r.json()["sources"].items(): | |
sourcesList.append(key) | |
return sourcesList | |
# setting 'now' to be the closest point of time until now | |
now = queryGraylog(nowTime) | |
# setting 'previous' to be the farthest point until now | |
previous = queryGraylog(previousTime) | |
# setting 'diff' as a list of devices which exist in previous, but not now | |
# e.g. 'devices which used to log, but do not log anymore to Graylog' | |
diff = set(previous).difference(now) | |
# converting the set to a list | |
diffList = list(diff) | |
# check to see if we need to send an alert or not. If so, send back to Graylog | |
if diffList == "": | |
# print "no differences. No stale devices for Graylog" | |
sys.exit(0) | |
else: | |
# stale devices detected. will alert | |
diffListCount = len(diffList) | |
staleSubject = str(diffListCount) + " stale device(s) detected" | |
staleBody = str(diffList) | |
print staleSubject | |
print staleBody | |
send_gelf_message(staleSubject,staleBody) | |
# now, we quit | |
sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment