使用Pexpect生成终端窗口和SSH命令

时间:2017-10-30 03:09:50

标签: python macos ssh terminal pexpect

我正在尝试使用Python和Pexpect模块做两件事:

  1. 打开多个终端窗口(在Mac上)以显示输出
  2. 向每个终端窗口发送单独的 ssh命令(每个窗口都将ssh到另一个主机,并运行另一个命令)
  3. 这是我目前的代码:

    import pexpect
    import time
    from subprocess import *
    
    command = "/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal ssh user@host"
    ssh_tunnel = pexpect.spawn (command)
    
    ssh_tunnel.expect ('Password:')
    time.sleep (0.1)
    ssh_tunnel.sendline ("password")
    time.sleep (60) #
    ssh_tunnel.expect (pexpect.EOF)
    

    我看到的问题是我能够打开一个新的终端应用程序,但是,该终端上没有运行任何命令。

    我也在尝试生成多个窗口时遇到问题。当我尝试这样做时:

    ssh_tunnel = pexpect.spawn("/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal")
    ssh_tunnel.expect ('test')
    
    ssh_tunnel2 = pexpect.spawn("/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal")
    ssh_tunnel2.expect ('test')
    

    我只生成一个终端窗口。

    我已经在python中尝试了子进程模块来生成多个终端窗口,并且工作正常,但我知道子进程不会处理ssh以及pexpect。

    子流程模块代码:

    from subprocess import *
    
    command = '/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal'
    new_terminal = Popen(command, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True)
    

0 个答案:

没有答案