Its been a long time since I was here, but I have worked on many scripts in the mean time and I think it would be nice to share a few!
I thought I would start with a small script I wrote about a year ago, the output of which was intended to be consumed by Splunk. Now I look at this, it could also be useful straight away for any work which wanted to keep a simple log file.
The reason I wrote this with 'time' as the only python import is because it was due to run on a hardware system with an old, cut back python installation. This may be an advantage for some, it should at least run on nearly any version of python out there.
The output is a nice timestamped line with all the key=value pairs displayed as strings. (quoted where necessary)
''' A script to write simple timestamped logs to a file. @author: HRH Example test usage below. Built with limited libraries due to the tiny python installation where this script is first intended to be used. ''' import time class SplunkLog: # Writes a line to the given file with the current timestamp # the data value should be a python dictionary where the key => val is # used for logtype=logtext def write_local_log(self,fh,data): t = time.localtime() logtime = str(t[0])+"-"+str(t[1]).zfill(2)+"-"+str(t[2]).zfill(2)+" "+str(t[3]).zfill(2)+":"+str(t[4]).zfill(2)+":"+str(t[5]).zfill(2) log_line = logtime + "\t" for row in data: for k , v in row.iteritems(): if " " in v: log_line += k + "=" + '"' + v + '"' + ",\t" else: log_line += k + "=" + v + ",\t" # Write the line, minus the last spacing and with added newline log_line = log_line.rstrip(",\t") + "\n" fh.write(log_line) ''' # # A usage example - remember to include or add the main class somewhere # # # # Main Loop # from sys import exit dummy_data = [] dummy_data.append({"severity" : "Warning","EventID": "Bad Login", "user" : "Test"}) dummy_data.append({"severity" : "Major","EventID": "Possible DoS", "user" : "Remote"}) s = SplunkLog() try: fh = open("splunk-test.txt",'a') except: print "Unable to open log file" exit(1) # If we are still here, then we can try write something into the file for log in dummy_data: s.write_local_log(fh, log) fh.close() exit(0) '''
No comments:
Post a Comment