【问题标题】:How to answer the questions asked by a bash script that has been called from a python script without human intervention [duplicate]如何在没有人工干预的情况下回答从 python 脚本调用的 bash 脚本提出的问题 [重复]
【发布时间】:2017-02-09 12:23:09
【问题描述】:

我有一个 bash 脚本,我通过 subprocess.call 从我的 python 脚本调用它;但是,该 bash 脚本在单独运行时会要求用户输入。我想通过我的 python 脚本本身来提供这个输入,而不是让用户手动回答它。

所以我基本上想从 python 脚本调用 bash 脚本,然后通过代码本身为执行该 bash 脚本时生成的问题之一提供输入。

这是我目前拥有的:

subprocess.call("/bin/bash "+sample.sh ,shell=True)

执行此操作,sample.sh 要求用户提示:

你叫什么名字?

我想从 python 代码本身传递该名称。

如果有任何指点,我将不胜感激。谢谢。

【问题讨论】:

  • 不是你希望得到的答案,但你为什么不把bash脚本变成python函数呢?因此,您可以轻松处理参数...我想补充一点,该子进程支持参数 -> Docs ,但(imo)在运行时输入不灵活。
  • 使用命令行参数传递名称,而不是提示在 bash 脚本中输入名称

标签: python linux bash shell


【解决方案1】:

pexpect 似乎完全符合您的要求。举个例子:

child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)

这是github repo。您可以使用以下命令安装pexpect

pip install pexpect

【讨论】:

    【解决方案2】:

    您可以使用bashexpect 解决该问题。这是一个进行远程 ssh 连接并执行ls -l / 的示例:

    export IP=<ip>
    export PAS=<passwd>
    expect -c 'spawn ssh root@$env(IP) "ls -l  /"; expect "password:"; send "$env(PAS)\n"; interact;'
    

    当expect接收到字符串“password:”时,它会发送变量PASS(密码)的内容,这样你就可以进行ssh连接并执行远程命令,而无需显式写入密码。

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 2018-04-09
      • 1970-01-01
      • 2019-10-31
      • 2016-12-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 2015-12-18
      相关资源
      最近更新 更多