How to determine what user and group a Python script is running as?

后端 未结 3 746
执笔经年
执笔经年 2021-01-01 11:10

I have a CGI script that is getting an \"IOError: [Errno 13] Permission denied\" error in the stack trace in the web server\'s error log.

As part of deb

相关标签:
3条回答
  • 2021-01-01 11:24

    You can use the following piece of code:

    import os
    print(os.getegid())
    
    0 讨论(0)
  • 2021-01-01 11:39

    os.getgid() and os.getuid() can be useful. For other environment variables, look into os.getenv. For example, os.getenv('USER') on my Mac OS X returns the username. os.getenv('USERNAME') would return the username on Windows machines.

    0 讨论(0)
  • 2021-01-01 11:42
    import os, getpass
    print getpass.getuser()
    

    Consider the following script.

    ---- foo.py ---- 
    import os, getpass
    print "Env thinks the user is [%s]" % (os.getlogin());
    print "Effective user is [%s]" % (getpass.getuser());
    

    Consider running the script.

    $ python ./foo.py
    

    results in

    Env thinks the user is [jds]
    Effective user is [jds]
    

    now run

    $ sudo -u apache python ./foo.py
    

    results in

    Env thinks the user is [jds]
    Effective user is [apache]
    

    As you can see, you these 2 calls os.getlogin() and getpass.getuser() are not the same thing. The underlying principle is how linux/and other unix's manages the running user.

    Consider

    $ id -u
    

    1000

    vs the effective id of the running process.

    $ sudo -u apache id -u
    

    33

    Note: this is exactly what web servers are doing when they start up. They are creating a sandbox (by forking/divorcing the psudo terminal etc), and running as another user. For an in-depth account of what is going on here: see the chapter on 'daemon processes' in the Advanced Programming in the UNIX environment book.

    Another good thread on the subject.

    0 讨论(0)
提交回复
热议问题