Python + pexpect - 如何建立ssh连接?

Python + pexpect - How to establish a ssh connection?

我一直在尝试通过 Python + pexpect 建立 ssh 连接,但我无法发送我想要的线路。

我认为这肯定是一个语法问题,但我不知道它发生在哪里。

#! /usr/bin/python # -*- encoding: utf-8 -*-
import re
import pexpect
import sys



child = pexpect.spawn ("gnome-terminal -e 'bash -c \"ssh -X user@localhost; exec bash\"'")
child.expect ("user@localhost\"''s password.*:\"'")
child.sendline ('xxyyzz')

print "OK"

问题是密码 'xxyyzz' 从未出现在终端上,所以我认为 child.sendline 不起作用,是语法问题。

您正在将输入传递给此处的 gnome-terminal 进程。那是行不通的,因为 ssh(从技术上讲,bash,但是 bash 的 stdin 也是 ssh 的)需要那个输入,不是 gnome-terminal.


无论如何,您可能很难让它可靠地工作。您可能应该考虑使用 Python SSH 库。

不错的选择包括:

  • Paramiko - 低级别 Python SSH 库
  • Fabric - 更高级别的库(在后台使用 Paramiko)

感谢您的建议,但我更愿意使用 pexpect。我找到了方法:

#!/usr/bin/env python
import pexpect
ssh_newkey = 'Are you sure you want to continue connecting'
# my ssh command line
child=pexpect.spawn('ssh username@server uname -a')
i=child.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
   print "I say yes"
   child.sendline('yes')
i=child.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
   print "I give password",
   child.sendline("xxxx")
   child.expect(pexpect.EOF)
elif i==2:
   print "I either got key or connection timeout"
pass
print child.before # print out the result

问候 !!!