【问题标题】:How do I use pexpect to run things in the background?如何使用 pexpect 在后台运行?
【发布时间】:2019-08-14 11:12:18
【问题描述】:

我在脚本中使用'Pexpect' 库,之后想进行一些操作。我正在做的事情如下:

def child():
        pexpect.spawn("ssh tranzmeo@192.168.21.110")
        child.expect(".*password.*")
        child.sendline('tranzmeo1@#')
        print(child.before)
        child.interact()
        return

这是我从另一个文件(我称之为训练)调用的函数。当我运行训练时,child() 被调用,但它立即停止程序并进入tranzmeo 控制台,我没有'不想要。我需要 ssh 进入它并在 tranzmeo 的后台做一些操作。如何使用 pexpect 做到这一点?

我的operation如下(仅供参考):

def scp(tensorflow_file_location_temp ,tensorflow_file_loc)
        child = pexpect.spawn("scp -r " + tensorflow_file_location_temp + "models@192.168.21.117:" + tensorflow_file_location )
        child.expect(".*password.*")
        child.sendline('Tranzmeo1@#')
        child.interact()

【问题讨论】:

  • 如果环境允许,您可以创建一个 ssh 密钥,将其 scp 到主机并允许无需密码的身份验证。这应该消除尝试将密码(位于纯文本中)提供给 ssh 进程的需要。
  • 我还有其他操作,不只是scp!
  • 您可以简单地使用 ssh 运行其他命令。用法:ssh @

标签: python ssh pexpect


【解决方案1】:

.interact()gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed.

如果你不想这样,就不要打电话!您想继续使用从pexpect.spawn("ssh tranzmeo@192.168.21.110") 返回的对象(您发布的代码并未将其分配给child,我认为这是一个复制粘贴错误):

child.sendline("scp -r " + tensorflow_file_location_temp + "models@192.168.21.117:" + tensorflow_file_location)

但你应该设置 ssh 密钥,然后你就可以在没有密码和 pexpect 的情况下通过simply running scp 做你想做的事情。

【讨论】:

  • 您好,我知道scp可以通过child.sendline完成,但是如果我需要做一些涉及其他操作的功能呢?
  • 我不确定您还面临什么其他问题。在这里,您问为什么要进入远程控制台,答案是由于调用interact 而发生这种情况。也许是一个单独的问题,其中包含有关您尝试做的更多详细信息的顺序..
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 2020-10-24
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多