【问题标题】:How to determine what user and group a Python script is running as?如何确定 Python 脚本作为哪个用户和组运行?
【发布时间】:2011-03-03 19:22:38
【问题描述】:

我的 CGI 脚本在 Web 服务器错误日志的堆栈跟踪中收到 "IOError: [Errno 13] Permission denied" 错误。

作为调试此问题的一部分,我想在脚本中添加一点代码,以将脚本运行的用户和(尤其是)组打印到错误日志(可能是 STDERR)中。

我知道我可以将值打印到sys.stderr,但是我如何确定脚本运行的用户和组?

(我对组特别感兴趣,所以$USER 环境变量无济于事;CGI 脚本设置了 setgid 位,因此它应该作为组“列表”而不是 Web 服务器的“www”运行-data”——但我需要代码来看看这是否真的发生了。)

【问题讨论】:

    标签: python unix permissions


    【解决方案1】:
    import os, getpass
    print getpass.getuser()
    

    考虑以下脚本。

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

    考虑运行脚本。

    $ python ./foo.py
    

    结果

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

    现在运行

    $ sudo -u apache python ./foo.py
    

    结果

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

    如您所见,这两个电话os.getlogin()getpass.getuser() 不是一回事。 基本原理是linux/和其他unix如何管理运行用户。

    考虑

    $ id -u
    

    1000

    vs 正在运行的进程的有效id。

    $ sudo -u apache id -u
    

    33

    注意:这正是 Web 服务器启动时所做的事情。他们正在创建一个沙箱(通过分叉/分离 psudo 终端等), 并以另一个用户身份运行。要深入了解这里发生的事情:请参阅Advanced Programming in the UNIX environment 书中关于“守护进程”的章节。

    Another good thread 关于这个主题。

    【讨论】:

      【解决方案2】:

      您可以使用以下代码:

      import os
      print(os.getegid())
      

      【讨论】:

      • 这会返回 group 而不是 user 对吗?来自文档:[This returns] the effective group id of the current process. This corresponds to the “set id” bit on the file being executed in the current process..
      • 是的,它是组的 id 而不是用户。
      • os.geteuid() 返回有效的用户 id
      【解决方案3】:

      os.getgid()os.getuid() 可能很有用。对于其他环境变量,请查看os.getenv。例如,我的 Mac OS X 上的 os.getenv('USER') 返回用户名。 os.getenv('USERNAME') 将返回 Windows 机器上的用户名。

      【讨论】:

      • 你也可以看看 getpass.getuser()。
      • 我同意,getpass.getuser() 获取登录名,一般是你要找的!
      猜你喜欢
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2019-12-15
      • 2013-05-01
      相关资源
      最近更新 更多