RailsSon
RailsSon

Reputation: 20637

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

Upvotes: 5

Views: 4667

Answers (3)

Francois Scheurer
Francois Scheurer

Reputation: 21

You can find a script here to log all 'bash' commands/builtins into a text-file or a 'syslog' server without using a patch or a special executable tool.

You can also write directly without syslog to a logfile.

It is very easy to deploy, as it is a simple shell script that need to be called once at the initialization of the 'bash'.

Upvotes: 2

holygeek
holygeek

Reputation: 16185

Check out script: http://bashshell.net/commands/using-the-script-command/

It records everything that appear on the terminal to a file, and iirc it can play back the recorded session.

You can set this as the user's shell to make it record everything upon login.

Upvotes: 4

wkl
wkl

Reputation: 79893

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.

Upvotes: 8

Related Questions