如何使用Pexpect停止通过SSH返回

0 投票
2 回答
1796 浏览
提问于 2025-04-15 22:09

我正在尝试使用 pexpect 通过 SSH 连接到另一台电脑,但我不想返回到原来的电脑。我的代码是:

#!/usr/bin/python2.6

import pexpect, os

def ssh():

    # Logs into computer through SSH
    ssh_newkey = 'Are you sure you want to continue connecting'
    # my ssh command line
    p=pexpect.spawn('ssh build@10.51.11.10')

    i=p.expect([ssh_newkey,'password:',pexpect.EOF])
    p.sendline("password")
    i=p.expect('-bash-3.2')

    print os.getcwd()
ssh()

这段代码让我可以通过 SSH 连接到那台电脑,但当我运行 os.getcwd() 时,pexpect 却把我带回了原来的电脑。你看,我想要连接到另一台电脑并使用他们的环境,而不是通过 pexpect 把我的环境带过去。有没有人能建议我怎么解决这个问题,或者提供一个替代的方法。

谢谢

2 个回答

0

你的实例在另一台机器上是 p。你可以用 p.sendline 发送你想在另一台机器上执行的命令,然后用 p.expect 来等待结果。在上面提到的情况下,

p.sendline("pwd && hostname")
p.expect("-bash-3.2") # although its better to set the prompt yourself so that this can be ported to any machine
response = p.before
print "received response [[" + response + "]]"

试试看这个。另外,你也可以试试 pxssh 这个模块,它可以用 Python 来进行 SSH 连接。这个模块是基于 pexpect 的,里面有你需要的所有方法,可以完全满足你的需求。

1

启动 ssh 的过程永远只会在它运行的那台电脑上进行。当你通过 ssh 连接到另一台电脑时,你实际上是在那台电脑上启动了一个新的进程。这个进程是完全独立的,属于另一种程序。如果你想在远程的机器上做任何事情,你必须通过连接发送要执行的命令,或者把你想运行的程序复制过去并在那台电脑上执行。

撰写回答