running a command as a super user from a python script(从 python 脚本以超级用户身份运行命令)
问题描述
所以我正在尝试使用子进程从 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 脚本以超级用户身份运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 python 脚本以超级用户身份运行命令
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
