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

问题描述 投票:1回答:1

我正在尝试创建一个简单的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()

我希望在输入'su'命令后在给定的密码提示中输入'password_to_enter',但事实并非如此。我尝试给它正确的密码,但仍然无法正常工作。

我究竟做错了什么?

PS:我在Mac上

python-3.x shell command-line subprocess output
1个回答
0
投票

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

su: must be run from a terminal

这是因为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)

有一个名为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("#")
© www.soinside.com 2019 - 2024. All rights reserved.