如何在Python中的终端密码提示中输入密码

Fed*_*uci 4 shell command-line subprocess python-3.x output

我正在尝试制作一个简单的Python脚本,在使用“su”命令(或任何其他需要管理员权限或只需要密码才能执行的命令)后在命令行中输入给定的密码。

我尝试使用 Subprocess 模块以及 pynput 来实现此目的,但一直无法弄清楚。

import subprocess
import os

# os.system('su') # Tried using this too

process = subprocess.Popen('su', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write(b"password_to_enter")
print(process.communicate()[0])
process.stdin.close()
Run Code Online (Sandbox Code Playgroud)

我原本希望在输入“su”命令后在给定的密码提示中输入“password_to_enter”,但事实并非如此。我也尝试给它正确的密码,但仍然不起作用。

我究竟做错了什么?

PS:我用的是Mac

Mic*_*ers 7

su命令期望从终端读取。在我的 Linux 机器上运行上面的示例会返回以下错误:

su: must be run from a terminal
Run Code Online (Sandbox Code Playgroud)

这是因为su试图确保它是从终端运行的。您可以通过分配pty并自行管理输入和输出来绕过此问题,但正确执行此操作可能非常棘手,因为在 su 提示输入密码之前您无法输入密码。例如:

import subprocess
import os
import pty
import time

# Allocate the pty to talk to su with.
master, slave = pty.openpty()

# Open the process, pass in the slave pty as stdin.
process = subprocess.Popen('su', stdin=slave, stdout=subprocess.PIPE, shell=True)

# Make sure we wait for the "Password:" prompt.
# The correct way to do this is to read from stdout and wait until the message is printed.
time.sleep(2)

# Open a write handle to the master end of the pty to write to.
pin = os.fdopen(master, "w")
pin.write("password_to_enter\n")
pin.flush()

# Clean up
print(process.communicate()[0])
pin.close()
os.close(slave)
Run Code Online (Sandbox Code Playgroud)

有一个名为pexpect 的库,它使与交互式应用程序的交互变得非常简单:

import pexpect
import sys

child = pexpect.spawn("su")
child.logfile_read = sys.stdout
child.expect("Password:")
child.sendline("your-password-here")
child.expect("#")
child.sendline("whoami")
child.expect("#")
Run Code Online (Sandbox Code Playgroud)