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
#
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.

  • Great idea using logname. Sometimes it's difficult to see the simplest solution ;). – Jakub Pasoń Mar 27 '16 at 10:09
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.

  • do you mean 'who | awk ..." – mahatmanich Mar 27 '16 at 9:47
  • 1
    No, I mean exectly what I wrote. who | awk will not work, because it will display all users that are logged in. Invoking who with two parameters is a nice trick, which displays only information about user who owns your terminal (so the one you su-ed from). – Jakub Pasoń Mar 27 '16 at 9:55
  • Anyway, using logname, as suggested in another comment, seems to be the simplest solution. – Jakub Pasoń Mar 27 '16 at 10:04
  • who am i does not do anything on my debian system – mahatmanich Mar 27 '16 at 10:10
  • It works in OSX and Centos Linux. Maybe who -m works for you ? – Jakub Pasoń Mar 27 '16 at 10:12

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.