How to log all Bash commands by all users on a server?

For BASH shells, edit the system-wide BASH runtime config file:

sudo -e /etc/bash.bashrc

Append to the end of that file:

export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"'

Set up logging for "local6" with a new file:

sudo -e /etc/rsyslog.d/bash.conf

And the contents...

local6.*    /var/log/commands.log

Restart rsyslog:

sudo service rsyslog restart

Log out. Log in. Voila!

But I forgot about log rotation:

sudo -e /etc/logrotate.d/rsyslog

There is a list of log files to rotate the same way...

/var/log/mail.warn
/var/log/mail.err
[...]
/var/log/message

So add the new bash-commands log file in that list:

/var/log/commands.log

Save.


A process accounting system may be helpful in this regard, particularly the acct package that provides the lastcomm and ac commands.

The ac commands prints out statistics about users' connection time, in hours. This is the amount of time that the user has been connected to the system, either remotely via SSH or a serial terminal, or while on the console.

The lastcomm command displays information about the previously executed commands. The most recent entries are given at the top of the list. Also displayed is the total amount of CPU time that each process used.

An old tutorial that may be helpful is here:

http://www.linuxjournal.com/article/6144?page=0,1

Other accounting commands like last and so on can be found in this tutorial:

http://www.techrepublic.com/article/system-accounting-in-linux/1053377


You could use snoopy.

Snoopy logger may suit your purpose well. It is not intended to be unavoidable logging solution, but rather a helpful tool for diligent admins who prefer to keep track of their own actions.

Disclosure: I am snoopy maintainer.

Tags:

Logging

Bash