http://pastie.org/3559094 has a quick & dirty python script I knocked together to demonstrate it, using
the 'appscript' scripting bridge, because I really *really* hate writing applescript. You could probably
translate it pretty easily though, it's something like:
tell app "iTerm"
get tty of every session of every terminal
-- save it somewhere/do something with it.
end tell
The bit I didn't immediately find an answer to was which of the programs running on a given tty is the active/foreground
one? Basic logic suggests it should be the most recent/one with the highest PID, but if you C-z that and switch back to another,
it could get confused. There might be some other way to do it that I'm not aware of.
A less/more hacky approach would be to use/emulate a preexec style hook for your shell, which writes to a file in /tmp or whatever
the name of the thing you're about to execute. The postexec/prompt_command hook then removes the flle.
zsh has support for preexec functions built in, and there's http://www.twistedmatrix.com/users/glyph/preexec.bash.txt for bash
which emulates it via debug traps.
Hope some of this helps,
Tom.