1
tail -2 /root/.bashrc
export HISTTIMEFORMAT="%d/%m/%y %T "
export PROMPT_COMMAND='builtin history 1 >> /var/log/root.log' 

With this all the commands could be logged (even the ones that were in "sudo su -" ).

My question: How can I put username info in the history file, so not just the time will be logged, but the original user, who "sudo su -"'ed username is in the history files too (or process PID from it's shell, or any unique identifier)?

2 Answers2

4

When you start a root bash shell as sudo -i or sudo -s or sudo su (provided root's login shell is bash) or sudo bash, the original user is available as $SUDO_USER.

But when started as sudo su -, the environment is cleared by su, so you'll have to find another way to find the original user.

One way, if you've got the pstree command could be:

original_user=${SUDO_USER:-$(pstree -Alsu "$$" |
  sed -n "s/.*(\([^)]*\)).*($USER)[^(]*$/\1/p")}
export HISTTIMEFORMAT="<%F %T> (${original_user:-$USER}) [$$] "
export PROMPT_COMMAND='builtin history 1 >> /var/log/root.log'

The idea being to parse the output of pstree -Alsu "$$" which looks like:

init---xterm(user)---zsh---sudo(root)---su---bash---pstree

To extract the user.

  • great solution, thanks! i use even original_user=$(pstree -Alsu "$$" | sed -n "s/^[^\(]*(\([^)]*\)).*($USER)[^(]*$/\1/p") - in case s/b makes sudo -iu <user> several times – atti Feb 05 '18 at 19:40
1

You can't You might be able to hack something, see @StephaneChazelas's answer below.

The shell's history file is user specific. The sudo commands will be listed in your actual user's history. If you use sudo su - you are opening a new shell where you are logged in as root. Any commands run there will be in root's history file but there is no way of knowing who your user was before since that is in a completely different shell.

By the way, using sudo su - is completely pointless. Either use su - or, sudo -i both of which have the same result.

terdon
  • 242,166