How to Log all Bash History Commands to syslog or loganalyzer (/var/log/messages) in CentOS/RHEL

Thanks to TheGeekDiary

The Ask

The user wants to see the list of commands used in the syslog messages. This way the user can audit user activities written in bash_history.

The Solution

1. To log bash history to a syslog server, you can use the trap feature provided by Bash. Append the following lines into either the per-user or system-wide bash profile; ~/.bash_profile and /etc/profile file.

PORT=`who am i | awk '{ print $5 }' | sed 's/(//g' | sed 's/)//g'`
logger -p local7.notice -t "bash $LOGNAME $$" User $LOGNAME logged from $PORT
function history_to_syslog
declare cmd
declare p_dir
declare LOG_NAME
cmd=$(history 1)
cmd=$(echo $cmd |awk '{print substr($0,length($1)+2)}')
if [ "$cmd" != "$old_command" ]; then
logger -p local7.notice -- SESSION = $$, from_remote_host = $PORT,  USER = $LOG_NAME,  PWD = $p_dir, CMD = "${cmd}"
trap history_to_syslog DEBUG || EXIT
Note: This resolution spawns new process at each command logged so it might not be the best solution if your system is in a heavy load.

2. To save this log messages into a particular log file, add below line in /etc/syslog.conf (for CentOS/RHEL 4/5) or /etc/rsyslog.conf (for CentOS/RHEL 6/7):

local7.notice                           /var/log/cmd.log

This will also log all the commands in the /var/log/messages file. To avoid these commands to be logged in into the /var/log/messages file, add below line in /etc/syslog.conf (for CentOS/RHEL 4/5) or /etc/rsyslog.conf (for CentOS/RHEL 6/7):

*.info;mail.none;authpriv.none;cron.none;local7.!notice                     /var/log/messages

This will not log the messages with priority notice or higher in /var/log/messages file.

3. Run below command to apply this change:

For CentOS/RHEL 4/5

# service syslog restart

For CentOS/RHEL 6

# service rsyslog restart

For CentOS/RHEL 7

# systemctl restart rsyslog
Note: When a user login into the system without providing -, it will not check /etc/profile file and thus the commands will not be logged in the /var/log/cmd.log file. To log the commands after logging into the user without providing -, add the above trap in a file inside /etc/profile.d/ directory.
IMP Sites:

Hi All, I like to spend time on black and white screen with linux. I love to learn new things in linux specially in virtualization. Currently I am working on OpenStack like to dig deep.

Posted in Linux

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: