access user history as root

Hi,

I need to access a user's command history. However, the dilemma is that he is logged in and so his current history is not yet flushed to .bash_history file which gets flushed when he logs out. Is there a way I can still access his most recent history?

thank you,

S

if you are the root user, how about adding this line in your /etc/bashrc file:

export PROMPT_COMMAND='history -a'

this will flush bash_history after each command.

edit: some people might see this as a security risk, see this

Yogesh provides a really cool answer. But it works only after the user's next login or shell session. What if you want to do this in real time? You'd have to examine the user's shell's memory to see what commands have been run. It'd be a bit cryptic, but it can be done. Use gcore (provided with gdb) to dump the core. Make sure you have lots of free disk space in your current dir and then run gcore <pid>. After this, you can hunt and search with:

strings core.11342 | less # pid is an example

Start searching for the last line recorded in the user's history file; lines after that could be the ones you are looking for.

interesting thought. How about logging out the user session. This should flush the contents of his history into the file. Is it possible to force logout a user? Secondly, is it possible to flush his existing history in memory to file without logging him out?

really the history command should have a -u (user) option for the root that could take in a session/pid parameter as well..

There is a small issue with yogesh's approach. If you have multiple sessions open to a host then all will write to the same history file. this can cause potential issues..

Yes. Just kill the login process or shell (with -1).

Possibly. In theory you could "inject" a command to the user's TTY input stream. This command might be "exec $SHELL" for instance, which would flush the history to disk and resume the session pretty much as-is.