1

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?

1
  • 1
    Why would you log both in the DEBUG trap and in PROMPT_COMMAND? That would mean you're logging double anyway. – muru Jun 8 '18 at 3:56
2

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
1

I have a very similar issue. Since I don't want to create duplicates for the same issue, I'm going to post mine in here as well.

I used the trap logger syntax from dessert but am encountering a very odd followup message in my /var/log/messages file

I added this line at the end of my /etc/profile:

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

When I now tail /var/log/messages in a separate terminal window, it shows me the command I executed in the first terminal and adds a second line which looks like this:

Jun 13 11:42:34 vm-centos bash[1521]: root:nano /etc/profile
Jun 13 11:43:14 vm-centos bash[1524]: root:printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"

I guess that the second line wants to tell me that there is some kind of error but I cannot see any error. Do you have an idea, how I could get rid of the second line with the printf?

Thank in advance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.