【问题标题】:How to automate shell input with python?如何使用 python 自动化 shell 输入?
【发布时间】:2011-10-24 01:15:27
【问题描述】:

我正在使用 python 自动执行一些任务,但遇到了一些障碍。我正在自动化的任务之一需要用户在 shell 中输入。

要求您使用电子邮件地址作为参数运行命令(很简单),然后要求您使用该电子邮件地址的密码进行身份验证。如何模拟用户输入来提供密码?

之后还有一些菜单询问选项,输入只需反复按回车即可。这是如何模拟的?请记住,此窗口并不总是有焦点..

【问题讨论】:

    标签: python unix shell


    【解决方案1】:

    我不确定您在第二部分中要问什么,但可以使用 pexpect 模块控制子流程。例如:

    #!/usr/bin/env python
    
    import pexpect
    import sys
    
    # Get email and password somehow
    #email = ...
    #password = ...
    
    # Start the subprocess
    child = pexpect.spawn('mycommand %s' % email)
    # redirect output to stdout
    child.logfile_read = sys.stdout
    
    # Assumes the prompt is "password:"
    child.expect('password:')
    child.sendline(password)
    
    # Wait for the process to close its output
    child.expect(pexpect.EOF)
    

    【讨论】:

      【解决方案2】:

      看来您的想法有误。您只需通过管道向收件人发送一些字节(在您的情况下为 shell 脚本),这可以通过 subprocess 完成。

      【讨论】:

        【解决方案3】:

        我想你可以使用 expect 来做这个。

        【讨论】:

          猜你喜欢
          • 2017-02-24
          • 1970-01-01
          • 2022-08-18
          • 1970-01-01
          • 2016-08-10
          • 1970-01-01
          • 2017-07-26
          • 2021-07-24
          • 2012-02-22
          相关资源
          最近更新 更多