相关疑难解决方法(0)

从python脚本以超级用户身份运行命令

因此,我正在尝试使用子进程从python脚本中以超级用户身份运行进程.在ipython shell中就像是

proc = subprocess.Popen('sudo apach2ctl restart',
                        shell=True, stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

工作正常,但一旦我把它插入脚本,我开始得到:sudo: apach2ctl: command not found.

我猜这是由于sudo在ubuntu上处理环境的方式.(我也尝试sudo -E apche2ctl restartsudo env path=$PATH apache2ctl restart与无济于事)

所以我的问题基本上是,如果我想以apache2ctl restart超级用户身份运行,在需要时提示用户输入超级用户密码,我应该怎么做呢?我无意在脚本中存储密码.

编辑:

我已经尝试将命令作为字符串传递并标记为列表.在python解释器中,使用字符串我将正确地获得密码提示(仍然不像我原来的问题那样在python脚本中工作),列表只是给出了sudo的帮助屏幕.

编辑2:

所以我收集的是,当shell = True时,Popen将使用一些命令作为字符串,这需要

proc = subprocess.Popen(['sudo','/usr/sbin/apache2ctl','restart'])
Run Code Online (Sandbox Code Playgroud)

没有'shell = True'让sudo工作.

谢谢!

python sudo subprocess

41
推荐指数
6
解决办法
10万
查看次数

标签 统计

python ×1

subprocess ×1

sudo ×1