Ubuntu – bash history log all commands to syslog

bashbash-historylog

I am trying to log all commands ran by all users. I got a solution from Github

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

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

but if we just hit enter multiple times the log claims that we actually executed the command multiple times too. How can I avoid this?

Best Answer

There’s no need to use fc if you just need the current command line, as the shell variable BASH_COMMAND holds exactly that. I’d just trap the DEBUG signal and use this variable as before, e.g.:

trap 'echo "$USER":"$BASH_COMMAND" >>/path/to/log' DEBUG

This also has the advantage that it doesn’t write anything to the log if you just press Enterfc just reads the last entry from the history list. Unfortunately I wasn’t able to test your logger command on my system, but you sound like it worked fine, so this should work as well:

trap 'logger -p local1.notice -t bash -i -- "$USER":"$BASH_COMMAND"' DEBUG

Example run

Note how aliases like ls, empty lines (Enter) and typo’d commands are logged.

$ trap 'echo "$USER":"$BASH_COMMAND" >>/path/to/log' DEBUG
$ uname
Linux
$ pwd
/home/dessert
$ hostname
dessert’s plowhorse
$ ls
dir1 file1 file2
$ 
$ 
$ bahs
No command 'bahs' found, did you mean:
 Command 'bash' from package 'bash' (main)
 Command 'bats' from package 'bats' (universe)
bahs: command not found
$ cat /path/to/log
dessert:uname
dessert:pwd
dessert:hostname
dessert:ls --color=auto
dessert:bahs
dessert:cat /path/to/log
Related Question