所以我正在尝试使用子进程从 python 脚本中以 super 用户身份运行一个进程。在 ipython shell 中类似于
proc = subprocess.Popen('sudo apach2ctl restart',
shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
工作正常,但只要我将它粘贴到脚本中,我就会开始得到:sudo: apach2ctl: command not found
.
我猜这是由于 sudo 在 ubuntu 上处理环境的方式。 (我也试过 sudo -E apche2ctl restart
和 sudo env path=$PATH apache2ctl restart
无济于事)
所以我的问题基本上是,如果我想以 super 用户身份运行 apache2ctl restart
并在需要时提示用户输入 super 用户密码,我应该怎么做呢?我无意在脚本中存储密码。
编辑:
我尝试将命令作为字符串传递并标记为列表。在 python 解释器中,我会用一个字符串正确地得到密码提示(在 python 脚本中仍然不能像我原来的问题那样工作),一个列表只是给出了 sudo 的帮助屏幕。
编辑 2:
所以我收集到的是,虽然当 shell=True 时 Popen 会像字符串一样处理一些命令,但它需要
proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart'])
没有 'shell=True' 让 sudo 工作。
谢谢!
最佳答案
试试:
subprocess.call(['sudo', 'apach2ctl', 'restart'])
子进程需要访问真正的 stdin/out/err 才能提示您,并读取您的密码。如果将它们设置为管道,则需要自己将密码输入该管道。
如果你不定义它们,那么它会抓取 sys.stdout 等...
关于python - 从 python 脚本以 super 用户身份运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/567542/