How do I log every command executed by a user?

Solution 1:

Add this line to your pam config responsible for logins (its system-auth on redhat based distros)

session    required     pam_tty_audit.so enable=*

To find out what was done, you can use.

ausearch -ts <some_timestamp> -m tty -i

This produces an output like this:

 type=TTY msg=audit(11/30/2011 15:38:39.178:12763684) : tty pid=32377 uid=root
 auid=matthew major=136 minor=2 comm=bash data=<up>,<ret>

The only downside to this is is can be a little bit difficult to read, but it is much better than most proposed solutions since in theory it could be used to record an entire session, warts n all.

Edit: Oh and you can use aureport to generate a list that can be more helpful.

# aureport --tty
...
12. 11/30/2011 15:50:54 12764042 501 ? 4294967295 bash "d",<^D>
13. 11/30/2011 15:52:30 12764112 501 ? 4294967295 bash "aureport --ty",<ret>
14. 11/30/2011 15:52:31 12764114 501 ? 4294967295 bash <up>,<left>,<left>,"t",<ret>

Solution 2:

The best solution to your problem would be Linux' built-in audit system. Use man 8 auditd or check this page for more information: http://linux.die.net/man/8/auditd.

Also, you can check this tutorial - while it is slightly out of the scope of your question, it shows how the audit system works.


Solution 3:

You could use snoopy.

It is a simple command logging library, and not a proper audit solution (easily circumvented). Disclosure: I am current snoopy maintainer.


Solution 4:

A lesser known trick, but easily the most awesome is just to use the built-in audit capabilities of sudo. Sudo ships with a sudoreplay command that makes replaying sessions easy. It will even relay vim sessions (as you suggest).

Here's how to use it in a few easy steps:

  1. Install sudosh on your system; this is a shell wrapper around the sudo command that makes a user sudo themselves (not root) and can be used as a system login shell
  2. Enable sudo logging. Edit /etc/sudoers.d/sudosh: Defaults log_output Defaults!/usr/bin/sudoreplay !log_output Defaults!/sbin/reboot !log_output

  3. Add this command to /etc/shells to permit logins using it: /usr/bin/sudosh

    Tip: to prevent users from using other shells to login, remove those other shells from /etc/shells.

  4. Update the user foobar to use the sudosh shell. chsh -s /usr/bin/sudosh foobar

For more detailed information, see: https://github.com/cloudposse/sudosh/