#!/usr/bin/python # # Simple log rotation script for ModSecurity "Concurrent" logs. Basically, # we search through a directory tree for any directories named YYYYMMDD. If # the given directory name is older (based on its name) than our retention # period, remove it and all of its contents. # # This was easier and more readable to implement in Python than via "find". # # Written for Python 2.4.3 (RHEL5) but probably is fairly portable. # # v1.0 # # Ray Van Dolson import os import re import shutil import datetime # The top level log directory we'll start from. LOGDIR = "/var/log/httpd/modsec" # The number of days -- in addition to the current day, worth of logs to keep. # This should be an integer greater than or equal to 0. DAYS = 2 def main(): global LOGDIR, DAYS # An array to store YYYYMMDD strings of directories we wish to keep. keepdays = [] # Populate our array of days to keep. for x in range(0, DAYS+1): keepday = datetime.datetime.today() - datetime.timedelta(x) keepdays.append(keepday.strftime('%Y%m%d')) print "=" * 78 print "ModSecurity Cleanup" print "Days to keep: " + ', '.join(keepdays) print "=" * 78 print # Walk our tree, subdirectories first (bottom up). tree = os.walk(LOGDIR, topdown=False) # Regular expression pattern to match on 8 integers in a row (suitable for # matching YYYYMMDD) m = re.compile("^[0-9]{8}$") for root, dirs, files in tree: # This will give us the last component of the directory. d = os.path.split(root)[1] # Does this appear to be a YYYYMMDD directory? match = re.match(m, d) if match: if d not in keepdays: print "Deleting %s" % root shutil.rmtree(root) else: print "Preserving %s" % root pass print print "Finished" if __name__ == '__main__': main() # ex: set sw=4 sts=4 tw=78 ai showmatch: