Domanda

Quando si esegue uno script tramite sudo o su Mi vuole ottenere l'utente originale. Questo dovrebbe accadere indipendentemente multipli sudo o su viene eseguito all'interno di ogni altro e specificatamente sudo su -.

È stato utile?

Soluzione

Risultati:

Usa who am i | awk '{print $1}' O logname come altri metodi sono garantite.

Collegato come sé:

evan> echo $USER
evan
evan> echo $SUDO_USER

evan> echo $LOGNAME
evan
evan> whoami
evan
evan> who am i | awk '{print $1}'
evan
evan> logname
evan
evan>

sudo normale:

evan> sudo -s
root> echo $USER
root
root> echo $SUDO_USER
evan
root> echo $LOGNAME
root
root> whoami
root
root> who am i | awk '{print $1}'
evan
root> logname
evan
root>

sudo su -:

evan> sudo su -
[root ]# echo $USER
root
[root ]# echo $SUDO_USER

[root ]# echo $LOGNAME
root
[root ]# whoami
root
[root ]# who am i | awk '{print $1}'
evan
[root ]# logname
evan
[root ]#

sudo su -; su tom:

evan> sudo su -
[root ]# su tom
tom$ echo $USER
tom
tom$ echo $SUDO_USER

tom$ echo $LOGNAME
tom
tom$ whoami
tom
tom$ who am i | awk '{print $1}'
evan
tom$ logname
evan
tom$

Altri suggerimenti

Non c'è ideale risposta. Quando si cambia ID utente, l'ID utente originale non è di solito conservata, quindi le informazioni si perde. Alcuni programmi, come logname e who -m implementare un hack dove controllano per vedere quale terminale è collegato al stdin, e quindi controllare per vedere quale utente è connesso a quel terminale.

Questa soluzione spesso opere, ma non è infallibile, e certamente non dovrebbe essere considerato sicuro. Per esempio, immaginate se who emette il seguente:

tom     pts/0        2011-07-03 19:18 (1.2.3.4)
joe     pts/1        2011-07-03 19:10 (5.6.7.8)

tom utilizzato su per arrivare alla radice, e viene eseguito il programma. Se STDIN non viene reindirizzata, quindi un programma come logname uscita tom volontà. Se è reindirizzato (ad esempio, da un file) come:

logname < /some/file

Poi il risultato è "no login name", dal momento che l'ingresso non è il terminale. Più interessante ancora, però, è il fatto che l'utente potrebbe rappresentare come un diverso utente connesso. Dal momento che Joe è loggato su pts / 1, Tom potrebbe fingere di essere lui eseguendo

logname < /dev/pts1

Ora, si dice joe anche se Tom è colui che ha eseguito il comando. In altre parole, se si utilizza questo meccanismo in qualsiasi tipo di ruolo di sicurezza, tu sei pazzo.

Questa è una funzione ksh ho scritto su HP-UX. Non so come andrà a lavorare con Bash in Linux. L'idea è che il processo di sudo è in esecuzione come l'utente originale ei processi figli sono l'utente di destinazione. Dal ciclismo indietro attraverso processi padre, siamo in grado di trovare l'utente del processo originale.

#
# The options of ps require UNIX_STD=2003.  I am setting it
# in a subshell to avoid having it pollute the parent's namespace.
#
function findUser
{
    thisPID=$$
    origUser=$(whoami)
    thisUser=$origUser
    while [ "$thisUser" = "$origUser" ]
    do
        ( export UNIX_STD=2003; ps -p$thisPID -ouser,ppid,pid,comm ) | grep $thisPID | read thisUser myPPid myPid myComm
        thisPID=$myPPid
    done
    if [ "$thisUser" = "root" ]
    then
        thisUser=$origUser
    fi
    if [ "$#" -gt "0" ]
    then
        echo $origUser--$thisUser--$myComm
    else
        echo $thisUser
    fi
    return 0
}

So che la domanda iniziale era da molto tempo fa, ma la gente (come me) stanno ancora chiedendo e questo sembrava un buon posto per mettere la soluzione.

Come sull'utilizzo logname (1) per ottenere il nome di login dell'utente?

THIS_USER=`pstree -lu -s $$ | grep --max-count=1 -o '([^)]*)' | head -n 1 | sed 's/[()]//g'`

Questa è l'unica cosa che ha funzionato per me.

Funzione

di user1683793 FindUser () portato su bash ed esteso in modo ritorna nomi utente archiviati nelle librerie NSS pure.

#!/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"

ciclismo indietro e dare un elenco di utenti

in base alla risposta del user1683793

Per exlcuding processi non TTY, io saltare root come iniziatore della login. Non sono sicuro se questo può exlcude troppo in alcuni casi

#!/bin/ksh
function findUserList
{
    typeset userList prevUser thisPID thisUser myPPid myPid myTTY myComm
    thisPID=$$                 # starting with this process-ID
    while [ "$thisPID" != 1 ]  # and cycling back to the origin
    do
        (  ps -p$thisPID -ouser,ppid,pid,tty,comm ) | grep $thisPID | read thisUser myPPid myPid myTTY myComm
        thisPID=$myPPid
        [[ $myComm =~ ^su ]] && continue        # su is always run by root -> skip it
        [[ $myTTY == '?' ]] && continue         # skip what is running somewhere in the background (without a terminal)
        if [[ $prevUser != $thisUser ]]; then   # we only want the change of user
                prevUser="$thisUser"            # keep the user for comparing
                userList="${userList:+$userList }$thisUser"  # and add the new user to the list
        fi
        #print "$thisPID=$thisUser: $userList -> $thisUser -> $myComm " >&2
    done
    print "$userList"
    return 0
}

logname o who am i non mi ha dato la risposta desiderata, soprattutto non in liste più lunghe di su user1, su user2, su user3, ...

So che la domanda iniziale era da molto tempo fa, ma la gente (come me) stanno ancora chiedendo e questo sembrava un buon posto per mettere la soluzione.

Alternativa a chiamare più volte ps: effettuare una chiamata pstree

pstree -lu -s $$ | grep --max-count=1 -o '([^)]*)' | head -n 1

uscita (quando connesso come pari): (evan)

argomenti pstree:

  • -l: linee lunghe (non accorciamento)
  • -u: spettacolo quando cambia utente come (nome utente)
  • -s $$: Visualizza i genitori di questo processo

Prendi il primo cambiamento dell'utente (che è di accesso) con grep -o e head.

limitazione: il comando può non contenere alcuna parentesi () (non normalmente)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top