简体   繁体   English

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

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

The subprocess.Popen() function has a "env" parameter. subprocess.Popen()函数具有一个“ env”参数。 But it doesn't seem to have the desired effect with sudo. 但是使用sudo似乎没有达到预期的效果。 This is what I get when I do this in the interactive Python shell: 这是在交互式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'

The message is distracting, so let me explain. 信息令人分心,所以让我解释一下。 I'm forced to use ancient CVS and the environment variable tells it to use ssh to connect to the server, rather than the default which sadly is rsh. 我被迫使用古老的CVS,环境变量告诉它使用ssh连接到服务器,而不是使用默认值rsh。 It also needs an environment variable called CVS_ROOT, but fortunately there's a "-d" option for that, but none for the CVS_RSH that I know of. 它还需要一个名为CVS_ROOT的环境变量,但是幸运的是,有一个“ -d”选项,但对于我所知道的CVS_RSH却没有。

Interestingly enough, if I do: 有趣的是,如果我这样做:

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'

Maybe this worked because echo wasn't actually started as a child process? 也许这是因为回声实际上不是作为子进程开始而起作用的? Is it possible to pass an environment to a process executed as another user with sudo? 是否可以通过sudo将环境传递给以其他用户身份执行的进程?

This doesn't seem possible using the env parameter. 使用env参数似乎无法实现。 The solution seems to be to just pass the environment as I was doing on the shell, for example: 解决方案似乎是像在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)

The weird thing is, if I do this in a Python CGI script, I can see: 奇怪的是,如果我在Python CGI脚本中执行此操作,则可以看到:

cvs [checkout aborted]: cannot exec ssh: Permission denied cvs [结帐中止]:无法执行ssh:权限被拒绝

cvs [checkout aborted]: end of file from server (consult above messages if any) cvs [结帐中止]:服务器中文件的末尾(如果有,请咨询以上消息)

But if I try on the interactive Python shell, it goes past this, so it must be another weird (because the user has permission to ssh) issue, unrelated to this question. 但是,如果我尝试使用交互式Python Shell,它将超越此范围,因此它一定是另一个奇怪的问题(因为用户有权使用ssh),与该问题无关。

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

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