How To Log Your Bash History With Syslog

Tags: , , , , , , ,

Prior to Bash 4.1 logging to syslog required either 3rd party patches, wrappers or clever hacks to glean command history information and send it to syslog. Until bash 4.1 becomes available for the majority of distributions these workaround and hacks are still useful to some who wish to obtain syslog functionality without altering, upgrading and maintaining bash manually.

Trap Method

Drop the following snippet into either the per-user or system-wide bash profile (~/.bash_profile or /etc/profile, respectively)

function log2syslog
{
   declare COMMAND
   COMMAND=$(fc -ln -0)
   logger -p local1.notice -t bash -i -- "${USER}:${COMMAND}"
}
trap log2syslog DEBUG

Read more about the trap method here

Prompt Method

This method logs by hacking the prompt command to call history and write to syslog.

PROMPT_COMMAND='history -a >(tee -a ~/.bash_history | logger -t "$USER[$$] $SSH_CONNECTION")'

You can read more about the prompt method here

Upgrade or Patch Bash

Bash version 4.1 support syslog natively, so if itโ€™s available in your distribution, or youโ€™re willing to hand compile this is likely your best bet.

bash-syslog patches are available to bring syslog features into bash 3.x