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

时间:2015-01-20 13:40:23

标签: python linux bash ssh

我一直试图通过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不起作用,并且是一个语法问题。

2 个答案:

答案 0 :(得分:1)

您在此处将输入传递给gnome-terminal进程。这不起作用,因为ssh(技术上,bash,但bash的stdin也是ssh)需要输入,而不是gnome-terminal


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

好的选择包括:

  • Paramiko - 低级Python SSH库
  • Fabric - 更高级别的图书馆(使用Paramiko)

答案 1 :(得分:0)

感谢您的建议,但我更喜欢使用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

问候!!!

相关问题