How to Track Shell Activities of Users in CentOS/RHEL

This post helps to save the command history of selected users to a centralized location for monitoring purposes.

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 hostory 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'

Log in to the same server via another ssh/putty session to make sure files are being created.