问题描述
所以我正在尝试使用子进程从 python 脚本中以超级用户身份运行一个进程.在 ipython shell 中类似于
So I'm trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like
proc = subprocess.Popen('sudo apach2ctl restart',
shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
工作正常,但只要我将它粘贴到脚本中,我就会开始得到:sudo: apach2ctl: command not found
.
works fine, but as soon as I stick it into a script I start getting: sudo: apach2ctl: command not found
.
我猜这是由于 sudo 在 ubuntu 上处理环境的方式.(我也试过 sudo -E apche2ctl restart
和 sudo env path=$PATH apache2ctl restart
无济于事)
I would guess this is due to the way sudo handles environments on ubuntu. (I've also tried sudo -E apche2ctl restart
and sudo env path=$PATH apache2ctl restart
with no avail)
所以我的问题基本上是,如果我想以超级用户身份运行 apache2ctl restart
并在需要时提示用户输入超级用户密码,我应该怎么做呢?我无意在脚本中存储密码.
So my question is basically, if I want to run apache2ctl restart
as super user that prompts the user for the super user password when required, how should I go about doing this? I have no intention of storing passwords in the script.
我尝试将命令作为字符串传递并标记为列表.在 python 解释器中,我会用一个字符串正确地得到密码提示(在 python 脚本中仍然不能像我原来的问题那样工作),一个列表只是给出了 sudo 的帮助屏幕.
I've tried passing in the commands as both a string and tokenized into a list. In the python interpreter, with a string I'll get the password prompt properly (still doesnt work in a python script as in my original problem), a list just gives the help screen for sudo.
编辑 2:
所以我收集到的是,虽然当 shell=True 时 Popen 会像字符串一样处理一些命令,但它需要
So what I gather is that while Popen will work with some commands just as strings when shell=True, it takes
proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart'])
没有 'shell=True' 让 sudo 工作.
without 'shell=True' to get sudo to work.
谢谢!
推荐答案
尝试给出 apache2ctl 的完整路径.
Try giving the full path to apache2ctl.
这篇关于从 python 脚本以超级用户身份运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!