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 -
.
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- JQ: Select when attribute value exists in a bash a
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
This is a
ksh
function I wrote on HP-UX. I don't know how it will work withBash
in Linux. The idea is that thesudo
process is running as the original user and the child processes are the target user. By cycling back through parent processes, we can find the user of the original process.I know the original question was from a long time ago but people (such as me) are still asking and this looked like a good place to put the solution.
cycling back and giving a list of users
based on user1683793's answer
By exlcuding non-TTY processes, I skip root as the initiator of the login. I'm not sure if that may exlcude too much in some case
logname
orwho am i
didn't give me the desired answer, especially not in longer lists ofsu user1
,su user2
,su user3
,...
I know the original question was from a long time ago but people (such as me) are still asking and this looked like a good place to put the solution.
There's no perfect answer. When you change user IDs, the original user ID is not usually preserved, so the information is lost. Some programs, such as
logname
andwho -m
implement a hack where they check to see which terminal is connected tostdin
, and then check to see what user is logged in on that terminal.This solution often works, but isn't foolproof, and certainly shouldn't be considered secure. For example, imagine if
who
outputs the following:tom
usedsu
to get to root, and runs your program. IfSTDIN
is not redirected, then a program likelogname
will outputtom
. If it IS redirected (e.g. from a file) as so:Then the result is "
no login name
", since the input isn't the terminal. More interestingly still, though, is the fact that the user could pose as a different logged in user. Since Joe is logged in on pts/1, Tom could pretend to be him by runningNow, it says
joe
even though tom is the one who ran the command. In other words, if you use this mechanism in any sort of security role, you're crazy.Results:
Use
who am i | awk '{print $1}'
ORlogname
as no other methods are guaranteed.Logged in as self:
Normal sudo:
sudo su - :
sudo su -; su tom :
How about using logname(1) to get the user's login name?
Alternative to calling ps multiple times: do one pstree call
output (when logged in as even):
(evan)
pstree arguments:
Get the first user change (which is login) with
grep -o
andhead
.limitation:the command may not contain any braces
()
(it does not normally)