【问题标题】:open terminal with sudo python [duplicate]用 sudo python 打开终端 [重复]
【发布时间】:2016-03-05 05:19:38
【问题描述】:

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

我有以下一小段代码:

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 做了我想要的。

【问题讨论】:

  • sudo 打开tty,默认不使用stdin。请改用sudo -S
  • 我想使用subprocess.Popen 而不是os.Popen
  • 不幸的是,接受的答案不是最佳答案;但问题是重复的,你会在那里找到好的答案。

标签: python python-2.7 subprocess


【解决方案1】:

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

【讨论】:

  • /etc/sudoers 中修复此问题似乎是正确的方法。查看command aliasses
  • 我在命令中使用了-Spopen.communicate(pass),但它并没有结束会话。
  • @SarvagyaPant:IIRC communicate() 不关闭标准输入。您需要将换行符与密码一起发送
  • @mrks 你能更新答案,建议在我的代码中使用pass + "\n"
  • 其实我错了:所有流都被communicate()关闭了
猜你喜欢
  • 2020-08-15
  • 1970-01-01
  • 2014-05-18
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2018-11-20
  • 1970-01-01
相关资源
最近更新 更多