簡體   English   中英

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進程。 那是行不通的,因為需要輸入而不是gnome-terminalssh (從技術上來說,是bash ,但bash的stdin也是ssh的)。


無論如何,要使此功能可靠地工作可能會很困難。 您可能應該考慮使用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

問候 !!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM