【问题标题】:Running a process as a different user from Python *and* print exit code以与 Python 不同的用户身份运行进程 *和*打印退出代码
【发布时间】:2020-11-16 16:21:26
【问题描述】:

我正在以 root 身份运行 python 脚本,从这个脚本中我想以 userA 身份在 linux 进程上运行。 关于如何做到这一点有很多答案 但我还需要打印从进程中收到的退出代码以及真正的问题。

有没有办法以 userA 身份运行进程并打印返回值?

os.system("su userA -c 'echo $USER'")
answer = subprocess.call(["su userA -c './my/path/run.sh'"])
print(answer)

【问题讨论】:

    标签: python linux


    【解决方案1】:

    当您正在运行一个脚本并且想要打印它的返回码时,您必须等到它的执行完成后再执行打印命令。 subprocess 模块允许您生成新进程,连接到它们的输入/输出/错误管道,并获取它们的返回码。 http://docs.python.org/library/subprocess.html

    在你的情况下:

        import subprocess
        process = subprocess.Popen('su userA -c ./my/path/run.sh', shell=True, stdout=subprocess.PIPE)
        process.wait()
        print process.returncode
    

    参考: https://stackoverflow.com/a/325474/13798864

    【讨论】:

      【解决方案2】:

      如果您使用os.fork(在孩子内部使用os.setuid),您可以使用os.waitpid 收集状态。

      pid = os.fork()
      if pid == 0:
          os.setgid(...)
          os.setgroups(...)
          os.setuid(...)
      
          # do something and collect the exit status... for example
          #
          # using os.system:
          #
          #      return_value = os.system(.....) // 256
          #
          # or using subprocess:
          #
          #      p = subprocess.Popen(....)
          #      out, err = p.communicate()
          #      return_value = p.returncode
          #
          # Or you can simply exec (this will not return to python but the 
          # exit status will still be visible in the parent).  Note there are 
          # several os.exec* calls, so choose the one which you want.
          #
          #      os.exec...
          #
          
          os._exit(return_value)
      
      pid, status = os.waitpid(pid, 0)
      print(f"Child exit code was {status // 256}")
      

      Here 我最近发布了一个相关问题的答案,该问题并没有过多关注返回值,但确实包含了您可能传递给 os.setuid 等调用的值的更多详细信息。

      【讨论】:

        猜你喜欢
        • 2012-11-29
        • 2010-12-18
        • 1970-01-01
        • 1970-01-01
        • 2018-04-17
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多