2015-12-01 282 views
0

我必须用python打开一个使用sudo的终端。考虑我的密码是pass,我需要在sudo critical-stack-intel pull的脚本中运行一个命令。用sudo python打开终端

我有以下小块代码:

import subprocess 
import shlex 

command = "sudo critical-stack-intel pull" 
popen = subprocess.Popen(shlex.split(command),stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
popen.communicate("pass") 
popen.wait() 
# print help(p) 

如果我运行该文件python myfile.py,它要求我为终端内的密码。这不是我想要的。我想让python处理我给的密码并正常运行。我如何完成这项工作?

编辑

使用popen.communicate(pass + "\n")sudo -S一起做了什么,我想要的。

+0

'sudo'打开tty,默认情况下它不使用stdin。用'sudo -S'代替 –

+0

看看这个:http://stackoverflow.com/questions/567542/running-a-command-as-a-super-user-from-a-python-script – nablahero

+0

我想要使用'subprocess.Popen'而不是'os.Popen'。 – Pant

回答

2

您可以使用-S选项sudo通过stdin传递密码。然而,最有可能的是,允许sudo使用/etc/sudoers访问critical-stack-intel而无需密码。

+1

在'/ etc/sudoers'中解决这个问题似乎是正确的方法。查看[命令别名](https://help.ubuntu.com/community/Sudoers#Command_Aliases) – Joost

+0

我在命令中使用了'-S'和'popen.communicate(pass)',但没有结束会话。 – Pant

+0

@SarvagyaPant:IIRC'沟通()'不关闭标准输入。你需要发送一个换行符和你的密码 –