How to Save Command history of Selected Users in Linux

A very powerful and cool command in Bash is history. Simply put, by default, Bash will store a history of all the commands you type. The value of the HISTSIZE variable determines the number of events preserved in the history list during a session. Although the default value for HISTSIZE is 500, you may want to set it to a more convenient value, such as 10000. When you exit from the shell, the most recently executed commands are saved in the file given by the HISTFILE variable (the default is .bash_history in your home directory). This post outlines the steps to save the command history of a specific user in Linux.

1. Create a new group monitor. Add users needs to be monitored into it as a secondary group.

# groupadd monitor
# usermod -a -G monitor [user] 

For example:

# usermod -a -G monitor opc
# id opc
uid=1000(opc) gid=1000(opc) groups=1000(opc),1002(admins),1003(monitor) 

2. Create directory /var/log/shelllogs where the shell history will be saved.

# mkdir /var/log/shelllogs
# chown root:monitor /var/log/shelllogs
# chmod 770 /var/log/shelllogs
# chmod +t /var/log/shelllogs

3. Create a script in /etc/profile.d with tweaked history format so that it will be exported everytime user logins.

# cat /etc/profile.d/history.sh
export HISTSIZE=10000
export HISTTIMEFORMAT='%F %T '
export HISTFILE=/var/log/shelllogs/$(who am i | awk '{print $1}';exit)-as-$(whoami)-$(date +%F-%T)
export PROMPT_COMMAND='history -a'

4. Edit /etc/bashrc and add following line by the end of the file.

test "$(ps -ocommand= -p $PPID | awk '{print $1}')" == 'script' || (script -f /var/log/shelllogs/$(who am i | awk '{print $1}';exit)-as-$(whoami)-$(date +%F-%T)_console.log)

Login to the same server via another ssh/putty session to ensure files are being created.

Related Post