Running Python script as root (with sudo) - what is the username of the effective user?

后端 未结 3 429
再見小時候
再見小時候 2020-12-29 09:00

I\'ve recently began using ConfigParser() for my python scripts to add some functionality to them for config files. I know how to use it but I have a problem. My script need

相关标签:
3条回答
  • 2020-12-29 09:36

    if you want to get the user that was logged in before launching the sudo command, it is stored in the SUDO_USER environment variable.

    import os
    sudo_username = os.getenv("SUDO_USER")
    home_dir = "/home/" + sudo_username
    

    You also have the SUDO_UID and SUDO_GID for the user id and group id.

    0 讨论(0)
  • 2020-12-29 09:41

    If you run your script with sudo (sudo myscript.py) then the environment variable $USER will be root and the environment variable $SUDO_USER will be the name of the user who executed the command sudo myscript.py. This following is simply a clarification of the previous post by Cédric Julien. Consider the following scenario:

    A linux user bob is logged into the system and possesses sudo privileges. He writes the following python script named myscript.py:

        #!/usr/bin/python
        import os
        print os.getenv("USER")
        print os.getenv("SUDO_USER")
    

    He then makes the script executable with chmod +x myscript.py and then executes his script with sudo privileges with the command:

    sudo ./myscript.py

    The output of that program will be (using python 2.x.x):

        root
        bob
    

    If bob runs the program sans sudo privileges with

    ./myscript.py

    he will get the following output:

        bob
        None
    
    0 讨论(0)
  • 2020-12-29 09:44

    This doesn't work.

    homepath = os.path.expanduser("~/")
    

    So don't use it.

    You want this.

    username= os.environ["LOGNAME"]
    homepath = os.path.expanduser("~"+username+"/")
    

    http://docs.python.org/library/os.html#os.getlogin

    Or perhaps this.

     username= pwd.getpwuid(os.getuid())[0]
     homepath = os.path.expanduser("~"+username+"/")
    
    0 讨论(0)
提交回复
热议问题