繁体   English   中英

Python Popen:通过sudo将环境变量传递给以其他用户身份运行的命令

[英]Python Popen: pass environment variable to command running as another user with sudo

subprocess.Popen()函数具有一个“ env”参数。 但是使用sudo似乎没有达到预期的效果。 这是在交互式Python Shell中执行此操作时得到的:

import subprocess
env={"CVS_RSH":"ssh"}
command = "sudo -u user cvs -d user@1.8.7.2:/usr/local/ncvs co file.py"
p = subprocess.Popen(command, stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,env=env,shell=True)
(command_output, error_output) = p.communicate()
p.wait()

1
>>> error_output
b'cvs [checkout aborted]: cannot exec rsh: No such file or 
directory\ncvs [checkout aborted]: end of file from server (consult 
above messages if any)\n'

信息令人分心,所以让我解释一下。 我被迫使用古老的CVS,环境变量告诉它使用ssh连接到服务器,而不是使用默认值rsh。 它还需要一个名为CVS_ROOT的环境变量,但是幸运的是,有一个“ -d”选项,但对于我所知道的CVS_RSH却没有。

有趣的是,如果我这样做:

command = "sudo -u user echo $CVS_RSH"
env={"CVS_RSH":"something_else"}
p = subprocess.Popen(command, stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE,env=env,shell=True)
(command_output, error_output) = p.communicate()
p.wait()

0
>>> command_output
b'something_else\n'

也许这是因为回声实际上不是作为子进程开始而起作用的? 是否可以通过sudo将环境传递给以其他用户身份执行的进程?

使用env参数似乎无法实现。 解决方案似乎是像在shell上一样通过环境,例如:

command = "sudo -u user CVS_RSH=ssh 
    CVSROOT=:ext:user@2.8.7.2:/usr/local/ncvs cvs co dir/file.py"
p = subprocess.Popen(command, stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE,env=env,shell=True)

奇怪的是,如果我在Python CGI脚本中执行此操作,则可以看到:

cvs [结帐中止]:无法执行ssh:权限被拒绝

cvs [结帐中止]:服务器中文件的末尾(如果有,请咨询以上消息)

但是,如果我尝试使用交互式Python Shell,它将超越此范围,因此它一定是另一个奇怪的问题(因为用户有权使用ssh),与该问题无关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM