Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Command Logger

I was wondering, out of curiosity, if it is possible to code a bash script logs all the command run in a Bash/SSH session. I know history is suppose to log all the commands run but it seems to be very unreliable!

I have been messing about this morning and came up with the following bash script which does log what the user runs in the terminal but does not run all the commands correctly.

prompt_read() {
  echo -n “$(whoami)@$(hostname):$(pwd)~$ “
  read userinput
}

prompt_read

while :; do
  if [[ $userinput != exit ]]; then
    logger "logit $userinput"
    bash -c "$userinput"
    prompt_read
  else
    kill -1 $PPID
  fi
done

Is anyone aware of anything that logs commands better and more reliably than history

Cheers

like image 528
RailsSon Avatar asked Aug 25 '11 15:08

RailsSon


1 Answers

The reason why history seems unreliable to you is because it only writes to history at the end of a BASH session, so you could lose commands.

I have a few things in my bash profile:

HISTFILESIZE=10000 # how many lines of history to store in the history file

HISTSIZE=10000 # how many lines of history to store in a session ( I think )

HISTCONTROL=ignoredups # ignore duplicate commands

shopt -s histappend # append history, rather than having sessions obliterate existing history
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

The last few are the important ones, setting your PROMPT_COMMAND with history -a will make history append immediately, rather than post-session. And setting shopt -s histappend will make bash sessions append to the history file, rather than overwrite existing histories.

Some more info: http://linuxcommando.blogspot.com/2007/11/keeping-command-history-across-multiple.html

Additionally, if this is useful to you, you can change the name of the history file you use for a particular bash session with the HISTFILE environment variable.

like image 95
逆さま Avatar answered Sep 28 '22 16:09

逆さま