Ubuntu – Linux comprehensive command line history

command-line-interfaceUbuntu

I have Ubuntu server. On the server several users are allowed to operate. They use ssh.

I need to have command line history for all of them in one place showing the time, the user and the command. Also I like to prevent the users from editing the history file. Generally speaking I need to record what they do on the server and prevent them from modifying the records.

Is there any solution for this ?

Best Answer

I believe it should be possible. I'd start by creating one logfile per user (as I'm unsure of the side effects of sharing a pooled history file). So for the sake of example, I'm going to

mkdir /var/log/history
touch /var/log/history/soneil
chown root:soneil /var/log/history/soneil
chmod 660 /var/log/history/soneil

So I have a history file that's owned by root, but 'soneil' can write to.

Then, a little magic: chattr +a /var/log/history/soneil

Now 'soneil' can only append to history, it's otherwise immutable to all but root.

So I've got my log file prepped, I just need to use it.

in /etc/bashrc (on Ubuntu I notice this is /etc/bash.bashrc):

export HISTFILE=/var/log/history/$USER
readonly HISTSIZE
readonly HISTFILE
readonly HISTIGNORE
readonly HISTCONTROL

The readonly builtin is fairly self-explanatory, and I believe could be equally applicable to SvenW's function too.

Tested, this has the same problem as the normal history file; it's written at logout, and isn't timestamped. so ordering events would be messy. I think if I had to do this myself, I'd add

PROMPT_COMMAND="history -a;$PROMPT_COMMAND"
readonly PROMPT_COMMAND

to force history to be flushed to disk each time a new prompt is drawn. There's also a HISTTIMEFORMAT envar which will add timestamps to the history file, but in a rather non-pretty format (setting the var to a prettier format only affects the output of 'history', not the contents of the file itself).