Python模块pexpect - 如何连接到ssh服务器然后运行bash命令

时间:2017-04-02 11:50:00

标签: bash ssh spawn pexpect

我是新手,我无法找到问题的完整答案。所以我在这里问。 我使用python和pexpect模块连接到ssh服务器并运行一些命令。但是有些命令不起作用。我查看了文档,我可以看到运行如下命令:

ls -l | grep -i <Filter>

因为我必须使用spawn命令来运行带有

的bash脚本

child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')

但是,我连接服务器的方法是发送带有密钥的ssh命令:

p = pexpect.spawn("ssh -t -t NAME@IP -i ~/.ssh/Keyfile ")

所以我不能用里面的bash命令运行spawn命令(或者我可以吗?)

响应应该是密码请求,因为它会将我重定向到另一台计算机。

如何使用spawn命令,以便我可以使用密钥连接到服务器,输入重定向计算机的密码,然后运行bash命令。

注意:我试图找出bash部分。与服务器的连接和重定向+密码插入已经适合我。

1 个答案:

答案 0 :(得分:1)

您可以在下一行发送命令:

ssh = pexpect.spawn('ssh  -t -t NAME@IP -i ~/.ssh/Keyfile')
#You may write expect here to check if the ask if for password or some other error or the initial banner message
ssh.sendline('password')
#You may check if the password is successful
ssh.sendline('/bin/bash -c "ls -l | grep LOG > logs.txt"');