Randomize cron entries with python.

I use this to prevent network brownouts when heavy bandwidth usage is expected. The script only randomizes the minute and hour fields of the cron entry, but can very easily be modified so that it randomizes all or selected entries. The script also only modifies entries that use the commands in the target list – this is so you only modify things that you know you’re modifying.

This script is provided as is, and I probably won’t be supporting any further changes to it, but let me know if you update it!

#!/usr/bin/python
# Usage: ./randomize_crond <user\'s cron file to modify>
import re, os, sys, shutil, random
 
user = ''
path = '/var/spool/cron'
targets = ['/scripts/cpbackup',
           '/scripts/upcp',
           '/scripts/exim_tidydb',
           '/usr/sbin/exiqgrep',
           '/usr/local/cpanel/whostmgr/docroot/cgi/cpaddons_report.pl',
           '/usr/local/bandmin/ipaddrmap']
 
def getCommand(line):
    matches = re.search('(.*?\s){5}\s*(.*)', line)
    return matches.group(2)
 
def formatString(command, lines):
    parts = command.split(' ')
    if parts[0] in targets:
        changed = str(random.randint(0, 59)) \
            + ' ' + str(random.randint(0, 23)) \
            + ' * * * ' + command + '\n'
        print 'Modified: ' + changed
        return changed
    else:
        for item in lines:
            if command in item:
                return item
 
if len(sys.argv) == 2:
    user = sys.argv[1]
    random.seed(None)
    path = path +'/'+ user;
    filereader = open(path, 'r')
    lines = filereader.readlines()
    filereader.close()
    filewriter = open(path + '.temp', 'w')
    filewriter.writelines(map(lambda command: formatString(command, lines), 
                              map(getCommand, lines)))
    filewriter.close()    
    os.remove(path)
    shutil.copy(path + '.temp', path)
else:
    print 'Usage: ./randomize_crond <user\'s cron file to modify>'
This entry was posted in Programming and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.