I need to write data to a file that requires administrative rights. And I need this script to work without sudo, because I need the current username, and when I run it with sudo, it is replaced with 'root', which does not suit me:

import getpass print(getpass.getuser()) # Output: 'root' при запуске скрипта с sudo 

So my problem will be solved by one of two things: either how to change 'root' to the current username, or how to write data to the file with administrator privileges, implementing it in Python.

    1 answer 1

    It is more logical and easier to find out the name of the user who ran the sudo program.

    For example, in the process started by the sudo program, you can use the environment variable SUDO_USER , which, according to man sudo , is set by the sudo program in the name of the user who called it:

    SUDO_USER Set to the login name of the user who invoked sudo.


    in python, you can get the value of an environment variable, like so :

     import os print os.environ['SUDO_USER'] 
    • Yes thank you. So earned. About 'SUDO_USER' did not know. I'll have to learn linux ... - Flaffen
    • to know (and even remember) is not necessary. just hypothesize, check ( $ sudo env | grep $USER ) and find confirmation in the documentation ( $ man -P cat sudo | grep SUDO_USER ). - aleksandr barakin pm
    • In practice, he didn’t check, but, I think, it would not be difficult to fake the environment variable, if suddenly someone is very impatient, so neatly - andreymal
    • @andreymal, yes, often (but not always) the user who starts sudo can intentionally pass other values ​​of the environment variables to the target program. - aleksandr barakin