2

Can I print the username which is obtaining root access via su - on the root console upon obtaining root?

user1$ su -
password:

obtained root via user1
#
mahatmanich
  • 2,954
  • 3
  • 22
  • 23
  • 1
    See here: http://stackoverflow.com/questions/4598001/how-do-you-find-the-original-user-through-multiple-sudo-and-su-commands. – Massimo Mar 27 '16 at 00:11

2 Answers2

2

Previously I recommend the script below... I found a better way! :) Just exec:

logname

Also, you can use $SUDO_USER, but doesn't work if you are using sudo su -
By the way, who am i is like who -m

This script also does the work:

#!/bin/bash
curpid=`awk '/^PPid:/{print $2}' /proc/$BASHPID/status`
ppui=`awk '/^PPid:/{print $2}' /proc/$curpid/status`
ppui=`awk '/^PPid:/{print $2}' /proc/$ppui/status`
uid=`awk '/^Uid:/{print $2}' /proc/$ppui/status`
name=`cat /etc/passwd | grep $uid | awk -F: '{print $1}'`
echo $name

Call it through .bash_profile if you are using login shells or .bashrc if using interactive non-login shells.

chicks
  • 3,793
  • 10
  • 27
  • 36
1

who am i|awk '{print "Obtained root via "$1}'

Add it to root's .bashrc to execute when you su.

You can also try

pstree -p -u |grep "$$"

to see the whole chain of processes with usernames. This could be useful if you have nested su with multiple users.

Jakub Pasoń
  • 331
  • 1
  • 5