How do you find the original user through multiple

2020-01-25 04:34发布

When running a script via sudo or su I want to get the original user. This should happen regardless of multiple sudo or su runs inside of each other and specifically sudo su -.

8条回答
Animai°情兽
2楼-- · 2020-01-25 05:18

user1683793's findUser() function ported to bash and extended so it returns usernames stored in NSS libraries as well.

#!/bin/bash

function findUser() {
    thisPID=$$
    origUser=$(whoami)
    thisUser=$origUser

    while [ "$thisUser" = "$origUser" ]
    do
        ARR=($(ps h -p$thisPID -ouser,ppid;))
        thisUser="${ARR[0]}"
        myPPid="${ARR[1]}"
        thisPID=$myPPid
    done

    getent passwd "$thisUser" | cut -d: -f1
}

user=$(findUser)
echo "logged in: $user"
查看更多
beautiful°
3楼-- · 2020-01-25 05:20
THIS_USER=`pstree -lu -s $$ | grep --max-count=1 -o '([^)]*)' | head -n 1 | sed 's/[()]//g'`

That's the only thing that worked for me.

查看更多
登录 后发表回答