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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With