Python3在子进程之后写入控制台。

2024-06-09 08:58:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python3写一个脚本subprocess.call,并且该调用要求用户写入密码。 我希望脚本调用子进程,然后自动写入密码,但到目前为止我还没有成功。 如果有什么帮助的话,我在Linux机器上执行它。在

我试过用波彭和烟斗

p = Popen("Command that when executed requires me to input a password", shell=True, stdin=PIPE) p.stdin.write(PASSWORD.encode("UTF-8"))

这将给出一个错误,说明无法读取密码(这意味着至少它完成了整个过程)

正常情况下也是如此subprocess.call在

subprocess.call(COMMAND) sys.stdin.write(PASSWORD)

在本例中,它一直等到我按ENTER键,然后执行下一行。在


Tags: 用户脚本机器密码进程linuxstdinpassword
2条回答

当交互询问密码时,不希望从文件中读取密码,而只能从终端读取密码。在

在Unix/Linux上,请求密码的程序实际上是从/dev/tty读取的,而不是标准输入。一个简单的确认方法是:

echo password | path/to/command_asking_for_password

如果它阻止等待密码,则很可能是从/dev/tty读取密码的。在

能做什么?在

  • 阅读文档。有些程序有特殊的选项,可以直接将密码作为命令行参数传递,或者强制从stdin读取
  • 使用伪终端。在Linux/Unix世界之外,简单的重定向和不可移植性稍微复杂一些,但是pty的从属部分被程序视为其真正的/dev/tty。在

    import pty
    import os
    import subprocess
    ...
    master, slave = pty.openpty()
    p = Popen("Command that when executed requires me to input a password", shell=True, stdin=slave)
    os.write(master, PASSWORD.encode("UTF-8"))
    ...
    p.wait()
    os.close(master)
    os.close(slave)
    

尝试:

p1 = subprocess.Popen(['echo','PASSWORD'], stdout=PIPE)
subprocess.Popen("Command that when executed requires me to input a password", stdin=p1.stdout)
p1.stdout.close()

首先,将一些内容回送到管道中,管道用作第二个子流程的输入

相关问题 更多 >