Skip to content

Instantly share code, notes, and snippets.

@gjedeer
Created March 7, 2012 18:51
Show Gist options
  • Save gjedeer/1995089 to your computer and use it in GitHub Desktop.
Save gjedeer/1995089 to your computer and use it in GitHub Desktop.
Logging wrapper for any command
#!/usr/bin/python
#
# Some command in the system being called in mysterious conditions?
# Use the logging wrapper!
# It will log all calls of a command along with process tree
# ("stack trace" of all calling processes)
#
# Usage:
# pip install psutil
# mv /usr/bin/snoopedcommand /usr/bin/snoopedcommand_wrapped
# cp logging_wrapper.py /usr/bin/snoopedcommand
# chmod +x /usr/bin/snoopedcommand
# tail -f /tmp/call_dbg.log
#
import os, psutil, datetime, subprocess, sys
proc = psutil.Process(os.getpid())
i = 0
f = open('/tmp/call_dbg.log', 'a')
f.write("========== " + str(datetime.datetime.now()) + "\n")
cmdline = []
while proc.pid > 0:
if i == 0:
cmdline.append(proc.cmdline[1] + "_wrapped")
cmdline += proc.cmdline[2:]
f.write(('%2d\t' % i) + ' '.join(proc.cmdline) + "\n")
proc = proc.parent
i += 1
f.write("==========\n")
f.close()
#print cmdline
subprocess.Popen(cmdline, stdout=sys.stdout, stderr=sys.stderr).communicate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment