1*7330f729Sjoerg#!/usr/bin/env python 2*7330f729Sjoerg 3*7330f729Sjoerg"""CaptureCmd - A generic tool for capturing information about the 4*7330f729Sjoerginvocations of another program. 5*7330f729Sjoerg 6*7330f729SjoergUsage 7*7330f729Sjoerg-- 8*7330f729Sjoerg1. Move the original tool to a safe known location. 9*7330f729Sjoerg 10*7330f729Sjoerg2. Link CaptureCmd to the original tool's location. 11*7330f729Sjoerg 12*7330f729Sjoerg3. Define CAPTURE_CMD_PROGRAM to the known location of the original 13*7330f729Sjoergtool; this must be an absolute path. 14*7330f729Sjoerg 15*7330f729Sjoerg4. Define CAPTURE_CMD_DIR to a directory to write invocation 16*7330f729Sjoerginformation to. 17*7330f729Sjoerg""" 18*7330f729Sjoerg 19*7330f729Sjoergimport hashlib 20*7330f729Sjoergimport os 21*7330f729Sjoergimport sys 22*7330f729Sjoergimport time 23*7330f729Sjoerg 24*7330f729Sjoergdef saveCaptureData(prefix, dir, object): 25*7330f729Sjoerg string = repr(object) + '\n' 26*7330f729Sjoerg key = hashlib.sha1(string).hexdigest() 27*7330f729Sjoerg path = os.path.join(dir, 28*7330f729Sjoerg prefix + key) 29*7330f729Sjoerg if not os.path.exists(path): 30*7330f729Sjoerg f = open(path, 'wb') 31*7330f729Sjoerg f.write(string) 32*7330f729Sjoerg f.close() 33*7330f729Sjoerg return prefix + key 34*7330f729Sjoerg 35*7330f729Sjoergdef main(): 36*7330f729Sjoerg program = os.getenv('CAPTURE_CMD_PROGRAM') 37*7330f729Sjoerg dir = os.getenv('CAPTURE_CMD_DIR') 38*7330f729Sjoerg fallback = os.getenv('CAPTURE_CMD_FALLBACK') 39*7330f729Sjoerg if not program: 40*7330f729Sjoerg raise ValueError('CAPTURE_CMD_PROGRAM is not defined!') 41*7330f729Sjoerg if not dir: 42*7330f729Sjoerg raise ValueError('CAPTURE_CMD_DIR is not defined!') 43*7330f729Sjoerg 44*7330f729Sjoerg # Make the output directory if it doesn't already exist. 45*7330f729Sjoerg if not os.path.exists(dir): 46*7330f729Sjoerg os.mkdir(dir, 0700) 47*7330f729Sjoerg 48*7330f729Sjoerg # Get keys for various data. 49*7330f729Sjoerg env = os.environ.items() 50*7330f729Sjoerg env.sort() 51*7330f729Sjoerg envKey = saveCaptureData('env-', dir, env) 52*7330f729Sjoerg cwdKey = saveCaptureData('cwd-', dir, os.getcwd()) 53*7330f729Sjoerg argvKey = saveCaptureData('argv-', dir, sys.argv) 54*7330f729Sjoerg entry = (time.time(), envKey, cwdKey, argvKey) 55*7330f729Sjoerg saveCaptureData('cmd-', dir, entry) 56*7330f729Sjoerg 57*7330f729Sjoerg if fallback: 58*7330f729Sjoerg pid = os.fork() 59*7330f729Sjoerg if not pid: 60*7330f729Sjoerg os.execv(program, sys.argv) 61*7330f729Sjoerg os._exit(1) 62*7330f729Sjoerg else: 63*7330f729Sjoerg res = os.waitpid(pid, 0) 64*7330f729Sjoerg if not res: 65*7330f729Sjoerg os.execv(fallback, sys.argv) 66*7330f729Sjoerg os._exit(1) 67*7330f729Sjoerg os._exit(res) 68*7330f729Sjoerg else: 69*7330f729Sjoerg os.execv(program, sys.argv) 70*7330f729Sjoerg os._exit(1) 71*7330f729Sjoerg 72*7330f729Sjoergif __name__ == '__main__': 73*7330f729Sjoerg main() 74