[英]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
不起作用,並且是語法問題。
感謝您的建議,但我更喜歡使用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.