将多个输入传递到终端命令 Python

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

我有这个终端命令,我需要在 Python 中以编程方式运行:

awssaml get-credentials --account-id **** --name **** --role **** --user-name ****

它首先会询问您的密码,然后提示您输入两步验证码。我将这些作为 python 中的变量,只需将其传递给命令即可。

这是我尝试过的:

   argss=[str(password_entry.get()),str(twoFactorCode_entry.get())]
   p=subprocess.Popen(["awssaml", "get-credentials", "--account-id", "****", "--name", "****", "--role", "****", "--user-name", ID_entry.get()],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
   time.sleep(0.1)
   
   out=p.communicate('\n'.join(map(str,argss)).encode())

当我运行此命令时,控制台会打印出已输入密码,因为它显示

password: xxxxxxxxxxxx
,但随后它停止执行并且不显示正在传递的 2 因素代码。

对于让 2 因素代码也通过的我在哪里出错有什么想法吗?密码和 2 因素代码都在

argss
变量内。
password_entry.get()
是密码,
twoFactorCode_entry.get()
是 2 因素代码。

python
1个回答
0
投票

我建议使用类似 pexpect 的东西,因为它最终有点复杂。

import pexpect

p=pexpect.spawn('awssaml', ["get-credentials", "--account-id", "****", "--name", "****", "--role", "****", "--user-name", ID_entry.get()])
p.expect('<whatever the prompt is for password>')
p.sendline(str(password_entry.get()))
p.expect('<whatever the prompt is for 2 factor code>')
p.sendline(str(twoFactorCode_entry.get()))

pexpect
源自
expect
Tcl 库,它实际上是为自动化交互式 CLI 程序而设计的,与默认的 Python 子进程模块不同。

© www.soinside.com 2019 - 2024. All rights reserved.